diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 69ce82b80f42c..d8faa2a20130d 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -501,6 +501,7 @@ declare namespace ts.server.protocol { type OrganizeImportsScope = GetCombinedCodeFixScope; interface OrganizeImportsRequestArgs { scope: OrganizeImportsScope; + skipDestructiveCodeActions?: boolean; } interface OrganizeImportsResponse extends Response { body: readonly FileCodeEdits[]; @@ -736,7 +737,7 @@ declare namespace ts.server.protocol { * Definition response message. Gives text range for definition. */ interface DefinitionResponse extends Response { - body?: FileSpanWithContext[]; + body?: DefinitionInfo[]; } interface DefinitionInfoAndBoundSpanResponse extends Response { body?: DefinitionInfoAndBoundSpan; @@ -1725,9 +1726,14 @@ declare namespace ts.server.protocol { isFromUncheckedFile?: true; /** * If true, this completion was for an auto-import of a module not yet in the program, but listed - * in the project package.json. + * in the project package.json. Used for telemetry reporting. */ isPackageJsonImport?: true; + /** + * If true, this completion was an auto-import-style completion of an import statement (i.e., the + * module specifier was inserted along with the imported identifier). Used for telemetry reporting. + */ + isImportStatementCompletion?: true; /** * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, * that allows TS Server to look up the symbol represented by the completion item, disambiguating diff --git a/lib/tsc.js b/lib/tsc.js index bacfdc2d70464..3698d06d1a471 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -65,7 +65,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) { var ts; (function (ts) { ts.versionMajorMinor = "4.3"; - ts.version = ts.versionMajorMinor + ".0-beta"; + ts.version = "4.3.1-rc"; var NativeCollections; (function (NativeCollections) { function tryGetNativeMap() { @@ -2247,11 +2247,11 @@ var ts; this.objectFlags & 8 ? "TupleType" : this.objectFlags & 16 ? "AnonymousType" : this.objectFlags & 32 ? "MappedType" : - this.objectFlags & 2048 ? "ReverseMappedType" : + this.objectFlags & 1024 ? "ReverseMappedType" : this.objectFlags & 256 ? "EvolvingArrayType" : "ObjectType" : "Type"; - var remainingObjectFlags = this.flags & 524288 ? this.objectFlags & ~2367 : 0; + var remainingObjectFlags = this.flags & 524288 ? this.objectFlags & ~1343 : 0; return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); } }, @@ -3093,7 +3093,7 @@ var ts; }; } var reverseMappedProperties = {}; - if (objectFlags & 2048) { + if (objectFlags & 1024) { var reverseMappedType = type; reverseMappedProperties = { reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id, @@ -5167,7 +5167,7 @@ var ts; A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), - An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), @@ -5193,6 +5193,7 @@ var ts; A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), @@ -5279,7 +5280,7 @@ var ts; Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."), - The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."), + The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -5321,6 +5322,7 @@ var ts; The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), + Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."), 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), @@ -5569,14 +5571,13 @@ var ts; The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), - Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), @@ -5599,17 +5600,17 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), @@ -5694,7 +5695,7 @@ var ts; Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), @@ -5702,14 +5703,14 @@ var ts; _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), - A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), @@ -5771,7 +5772,7 @@ var ts; The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), - This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_2774", "This condition will always return true since this function appears to always be defined. Did you mean to call it instead?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), @@ -5798,7 +5799,7 @@ var ts; The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), - This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined_2801", "This condition will always return true since this '{0}' appears to always be defined."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), @@ -5807,6 +5808,9 @@ var ts; This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), + Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), + Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), 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}'."), @@ -5904,7 +5908,7 @@ var ts; This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), - This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_becaus_4115", "This parameter property must be rewritten as a property declaration with an 'override' modifier because it overrides a member in base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), 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."), @@ -5940,7 +5944,7 @@ var ts; Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), - Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), @@ -5953,12 +5957,14 @@ var ts; Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), - A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -6182,7 +6188,11 @@ var ts; Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), - Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -6230,6 +6240,7 @@ var ts; _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", undefined, undefined, true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", undefined, undefined, true), + Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), 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."), @@ -6271,7 +6282,7 @@ var ts; Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -6311,7 +6322,7 @@ var ts; JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), @@ -6895,11 +6906,11 @@ var ts; } } ts.couldStartTrivia = couldStartTrivia; - function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { - if (stopAtComments === void 0) { stopAtComments = false; } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (ts.positionIsSynthesized(pos)) { return pos; } + var canConsumeStar = false; while (true) { var ch = text.charCodeAt(pos); switch (ch) { @@ -6912,6 +6923,7 @@ var ts; if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case 9: case 11: @@ -6931,6 +6943,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === 42) { @@ -6942,6 +6955,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } break; @@ -6951,12 +6965,21 @@ var ts; case 62: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; case 35: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -8786,7 +8809,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 92) && parent.kind === 167; + return ts.hasSyntacticModifier(node, 16476) && parent.kind === 167; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -9062,7 +9085,7 @@ var ts; if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } ts.getNameOfDeclaration = getNameOfDeclaration; function getAssignedName(node) { @@ -9487,7 +9510,7 @@ var ts; } ts.isModifierKind = isModifierKind; function isParameterPropertyModifier(kind) { - return !!(ts.modifierToFlag(kind) & 92); + return !!(ts.modifierToFlag(kind) & 16476); } ts.isParameterPropertyModifier = isParameterPropertyModifier; function isClassMemberModifier(idToken) { @@ -10335,7 +10358,9 @@ var ts; } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { @@ -10534,7 +10559,7 @@ var ts; if (node.kind === 338 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, false, isInJSDoc(node)); } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -11840,6 +11865,10 @@ var ts; return node.kind === 177; } ts.isPartOfTypeQuery = isPartOfTypeQuery; + function isNamespaceReexportDeclaration(node) { + return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 261 && node.moduleReference.kind === 273; } @@ -12395,6 +12424,7 @@ var ts; parent.kind === 267 || parent.kind === 164 || parent.kind === 234 && node.kind === 202 || + parent.kind === 243 || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 62) { return parent; @@ -15126,6 +15156,10 @@ var ts; return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; + function getUseDefineForClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === 99 : compilerOptions.useDefineForClassFields; + } + ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return oldOptions !== newOptions && ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); @@ -15193,19 +15227,33 @@ var ts; } (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); } - } + }, + setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { + this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); + var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var cache = createSymlinkCache(cwd, getCanonicalFileName); - var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { - return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + var symlinks = ts.flatMap(files, function (sf) { + var pairs = sf.resolvedModules && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedModules.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) ? [res.resolvedFileName, res.originalPath] : undefined; + })); + return ts.concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] : undefined; }))); - })); + }); for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); @@ -16052,7 +16100,11 @@ var ts; var ts; (function (ts) { function createParenthesizerRules(factory) { + var binaryLeftOperandParenthesizerCache; + var binaryRightOperandParenthesizerCache; return { + getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName, @@ -16073,6 +16125,24 @@ var ts; parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType, parenthesizeTypeArguments: parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); }; + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, undefined, node); }; + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var binaryOperatorPrecedence = ts.getOperatorPrecedence(217, binaryOperator); var binaryOperatorAssociativity = ts.getOperatorAssociativity(217, binaryOperator); @@ -16277,6 +16347,8 @@ var ts; } ts.createParenthesizerRules = createParenthesizerRules; ts.nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; }, + getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; }, parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; }, parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; }, parenthesizeExpressionOfComputedPropertyName: ts.identity, @@ -17151,6 +17223,7 @@ var ts; case 155: case 141: case 145: + case 156: case 147: case 131: case 148: @@ -17219,15 +17292,15 @@ var ts; if (flags & 32) { result.push(createModifier(123)); } + if (flags & 16384) { + result.push(createModifier(156)); + } if (flags & 64) { result.push(createModifier(142)); } if (flags & 256) { result.push(createModifier(129)); } - if (flags & 16384) { - result.push(createModifier(156)); - } return result; } function createQualifiedName(left, right) { @@ -17284,7 +17357,7 @@ var ts; propagateChildFlags(node.questionToken); if (questionToken) node.transformFlags |= 1; - if (ts.modifiersToFlags(node.modifiers) & 92) + if (ts.modifiersToFlags(node.modifiers) & 16476) node.transformFlags |= 4096; if (initializer || dotDotDotToken) node.transformFlags |= 512; @@ -17841,7 +17914,7 @@ var ts; : node; } function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createBaseBindingLikeDeclaration(199, undefined, undefined, name, initializer); + var node = createBaseBindingLikeDeclaration(199, undefined, undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= @@ -23526,6 +23599,7 @@ var ts; case 324: case 325: case 326: + case 321: return visitNode(cbNode, node.tagName) || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); case 340: @@ -25174,11 +25248,14 @@ var ts; function parseParameterWorker(inOuterAwaitContext) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); if (token() === 107) { - var node_1 = factory.createParameterDeclaration(undefined, undefined, undefined, createIdentifier(true), undefined, parseTypeAnnotation(), undefined); + var node_1 = factory.createParameterDeclaration(decorators, undefined, undefined, createIdentifier(true), undefined, parseTypeAnnotation(), undefined); + if (decorators) { + parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } return withJSDoc(finishNode(node_1, pos), hasJSDoc); } - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); var savedTopLevel = topLevel; topLevel = false; var modifiers = parseModifiers(); @@ -26948,12 +27025,13 @@ var ts; } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var openBracePosition = scanner.getTokenPos(); if (parseExpected(18, diagnosticMessage) || ignoreMissingOpenBrace) { var multiLine = scanner.hasPrecedingLineBreak(); var statements = parseList(1, parseStatement); parseExpectedMatchingBrackets(18, 19, openBracePosition); - var result = finishNode(factory.createBlock(statements, multiLine), pos); + var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); if (token() === 62) { parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); nextToken(); @@ -26962,7 +27040,7 @@ var ts; } else { var statements = createMissingList(); - return finishNode(factory.createBlock(statements, undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, undefined), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -26987,11 +27065,13 @@ var ts; } function parseEmptyStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(26); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(98); var openParenPosition = scanner.getTokenPos(); parseExpected(20); @@ -26999,10 +27079,11 @@ var ts; parseExpectedMatchingBrackets(20, 21, openParenPosition); var thenStatement = parseStatement(); var elseStatement = parseOptional(90) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(89); var statement = parseStatement(); parseExpected(114); @@ -27011,20 +27092,22 @@ var ts; var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20, 21, openParenPosition); parseOptional(26); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(114); var openParenPosition = scanner.getTokenPos(); parseExpected(20); var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20, 21, openParenPosition); var statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(96); var awaitToken = parseOptionalToken(130); parseExpected(20); @@ -27060,34 +27143,37 @@ var ts; parseExpected(21); node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(kind === 242 ? 80 : 85); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); var node = kind === 242 ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(104); var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(115); var openParenPosition = scanner.getTokenPos(); parseExpected(20); var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20, 21, openParenPosition); var statement = doInsideOfContext(16777216, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { var pos = getNodePos(); @@ -27116,15 +27202,17 @@ var ts; } function parseSwitchStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(106); parseExpected(20); var expression = allowInAnd(parseExpression); parseExpected(21); var caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(108); var expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); if (expression === undefined) { @@ -27132,10 +27220,11 @@ var ts; expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } function parseTryStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(110); var tryBlock = parseBlock(false); var catchClause = token() === 82 ? parseCatchClause() : undefined; @@ -27144,7 +27233,7 @@ var ts; parseExpected(95); finallyBlock = parseBlock(false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { var pos = getNodePos(); @@ -27162,9 +27251,10 @@ var ts; } function parseDebuggerStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(86); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement() { var pos = getNodePos(); @@ -28531,7 +28621,8 @@ var ts; indent = 0; break; case 59: - if (state === 3 || !previousWhitespace && state === 2) { + if (state === 3 + || state === 2 && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { comments.push(scanner.getTokenText()); break; } @@ -28602,6 +28693,10 @@ var ts; return comments.join(""); } } + function isNextJSDocTokenWhitespace() { + var next = nextTokenJSDoc(); + return next === 5 || next === 4; + } function parseJSDocLink(start) { if (!tryParse(parseJSDocLinkPrefix)) { return undefined; @@ -29855,7 +29950,7 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsWithoutBuild = [ { name: "all", type: "boolean", @@ -30624,7 +30719,8 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins }, - ]); + ]; + ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsWithoutBuild); ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; }); ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); @@ -30634,7 +30730,7 @@ var ts; ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) { return ts.hasProperty(option, "transpileOptionValue"); }); - ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsOnlyBuild = [ { name: "verbose", shortName: "v", @@ -30662,7 +30758,8 @@ var ts; description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean" } - ]); + ]; + ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsOnlyBuild); ts.typeAcquisitionDeclarations = [ { name: "enableAutoDiscovery", @@ -30710,6 +30807,10 @@ var ts; return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations)); } ts.getOptionsNameMap = getOptionsNameMap; + var compilerOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1, @@ -30765,6 +30866,10 @@ var ts; return option.name; } function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { + var _a; + if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -30913,6 +31018,7 @@ var ts; return i; } ts.compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -30943,7 +31049,12 @@ var ts; function getBuildOptionsNameMap() { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts)); } + var buildOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap: getOptionsNameMap + }; var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: ts.buildOpts, unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, @@ -32428,13 +32539,24 @@ var ts; return typeRoots; } var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) { var traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined; + var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -32457,6 +32579,8 @@ var ts; trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); } } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -32467,17 +32591,31 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary: primary, + resolvedFileName: resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId: packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, result); + if (traceEnabled) + traceResult(result); + return result; + function traceResult(result) { + var _a; + if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { if (typeRoots && typeRoots.length) { if (traceEnabled) { @@ -32505,20 +32643,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = void 0; + var result_4; if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, undefined, undefined); - result = searchResult && searchResult.value; + result_4 = searchResult && searchResult.value; } else { var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; - result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, false, moduleResolutionState, true); - } - var resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, false, moduleResolutionState, true); } - return resolvedFile; + return resolvedTypeScriptOnly(result_4); } else { if (traceEnabled) { @@ -32558,21 +32692,20 @@ var ts; return result; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName); - } - ts.createModuleResolutionCache = createModuleResolutionCache; function createCacheWithRedirects(options) { var ownMap = new ts.Map(); var redirectsMap = new ts.Map(); return { - ownMap: ownMap, + getOwnMap: getOwnMap, redirectsMap: redirectsMap, getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, clear: clear, setOwnOptions: setOwnOptions, setOwnMap: setOwnMap }; + function getOwnMap() { + return ownMap; + } function setOwnOptions(newOptions) { options = newOptions; } @@ -32597,25 +32730,86 @@ var ts; } } ts.createCacheWithRedirects = createCacheWithRedirects; - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap }; + function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + var cache; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear }; + function getPackageJsonInfo(packageJsonPath) { + return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + if (!options.configFile) + return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + var ref = { + sourceFile: options.configFile, + commandLine: { options: options } + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options); + } + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) { + return { + getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, + clear: clear, + update: update, + }; + function clear() { + directoryToModuleNameMap.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap); + } function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); }); } + } + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + var preDirectoryResolutionCache = 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; } }); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + packageJsonInfoCache.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); + } function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } - function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { - var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - var result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; - } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); return { get: get, set: set }; @@ -32663,7 +32857,17 @@ var ts; } } } - ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + ts.createModuleResolutionCache = createModuleResolutionCache; + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache.clear(); + } + } + ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache) { var containingDirectory = ts.getDirectoryPath(containingFile); var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -32867,7 +33071,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; 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, state.resultFromCache); function tryResolve(extensions) { @@ -32925,7 +33129,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -32947,7 +33151,7 @@ var ts; } ts.pathContainsNodeModules = pathContainsNodeModules; function parseNodeModuleFromPath(resolved) { - var path = ts.normalizePath(resolved.path); + var path = ts.normalizePath(resolved); var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; @@ -32959,6 +33163,7 @@ var ts; } return path.slice(0, indexAfterPackageName); } + ts.parseNodeModuleFromPath = parseNodeModuleFromPath; function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; @@ -33032,21 +33237,43 @@ var ts; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c; var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) + trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) + trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + var directoryExists = ts.directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = ts.readJson(packageJsonPath, host); if (traceEnabled) { trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists); state.failedLookupLocations.push(packageJsonPath); } } @@ -33276,7 +33503,7 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations, state.resultFromCache); @@ -33309,13 +33536,13 @@ var ts; } } ts.classicNameResolver = classicNameResolver; - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { 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 state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, false); return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations, state.resultFromCache); } @@ -33796,6 +34023,7 @@ var ts; } if (node.kind === 298) { node.flags |= emitFlags; + node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -34986,9 +35214,9 @@ var ts; var saveCurrentFlow = currentFlow; for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { var typeAlias = delayedTypeAliases_1[_i]; - var host = ts.getJSDocHost(typeAlias); - container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1); })) || file; - blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file; + var host = typeAlias.parent.parent; + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -35495,7 +35723,7 @@ var ts; } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); + bindAnonymousDeclaration(node, 111551, getDeclarationName(node)); } else { var flags = ts.exportAssignmentIsAlias(node) @@ -36344,6 +36572,7 @@ var ts; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -36352,7 +36581,7 @@ var ts; var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384; var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); @@ -36532,6 +36761,7 @@ var ts; return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, + getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, argumentCount) { return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0); @@ -36697,14 +36927,14 @@ var ts; var autoType = createIntrinsicType(1, "any"); var wildcardType = createIntrinsicType(1, "any"); var errorType = createIntrinsicType(1, "error"); - var nonInferrableAnyType = createIntrinsicType(1, "any", 524288); + var nonInferrableAnyType = createIntrinsicType(1, "any", 131072); var intrinsicMarkerType = createIntrinsicType(1, "intrinsic"); var unknownType = createIntrinsicType(2, "unknown"); var undefinedType = createIntrinsicType(32768, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768, "undefined", 524288); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768, "undefined", 131072); var optionalType = createIntrinsicType(32768, "undefined"); var nullType = createIntrinsicType(65536, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536, "null", 524288); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536, "null", 131072); var stringType = createIntrinsicType(4, "string"); var numberType = createIntrinsicType(8, "number"); var bigintType = createIntrinsicType(64, "bigint"); @@ -36728,7 +36958,7 @@ var ts; var voidType = createIntrinsicType(16384, "void"); var neverType = createIntrinsicType(131072, "never"); var silentNeverType = createIntrinsicType(131072, "never"); - var nonInferrableType = createIntrinsicType(131072, "never", 2097152); + var nonInferrableType = createIntrinsicType(131072, "never", 524288); var implicitNeverType = createIntrinsicType(131072, "never"); var unreachableNeverType = createIntrinsicType(131072, "never"); var nonPrimitiveType = createIntrinsicType(67108864, "object"); @@ -36740,14 +36970,14 @@ var ts; var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - emptyJsxObjectType.objectFlags |= 4096; + emptyJsxObjectType.objectFlags |= 2048; var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); emptyGenericType.instantiations = new ts.Map(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - anyFunctionType.objectFlags |= 2097152; + anyFunctionType.objectFlags |= 524288; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -37350,7 +37580,7 @@ var ts; return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, false); } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { - return !(compilerOptions.target === 99 && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === 99 && useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -37366,7 +37596,7 @@ var ts; return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === 99 && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === 99 && useDefineForClassFields && ts.getContainingClass(declaration) && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, true); @@ -37486,7 +37716,7 @@ var ts; return requiresScopeChangeWorker(node.name); case 164: if (ts.hasStaticModifier(node)) { - return target < 99 || !compilerOptions.useDefineForClassFields; + return target < 99 || !useDefineForClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -37780,7 +38010,7 @@ var ts; return undefined; } if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === 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)); return undefined; @@ -38077,8 +38307,7 @@ var ts; } } function getDeclarationOfAliasSymbol(symbol) { - var _a; - return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(isAliasSymbolDeclaration); + return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration); } function isAliasSymbolDeclaration(node) { return node.kind === 261 @@ -38277,7 +38506,7 @@ var ts; return undefined; } var suppressInteropError = name.escapedText === "default" && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -39235,7 +39464,7 @@ var ts; var result; var _loop_8 = function (location) { if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, undefined, true)) { return { value: result }; } } @@ -39246,7 +39475,7 @@ var ts; } case 257: var sym = getSymbolOfNode(location); - if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) { + if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, undefined, true)) { return { value: result }; } break; @@ -39270,7 +39499,7 @@ var ts; if (typeof state_2 === "object") return state_2.value; } - return callback(globals); + return callback(globals, undefined, true); } function getQualifiedLeftMeaning(rightMeaning) { return rightMeaning === 111551 ? 111551 : 1920; @@ -39286,11 +39515,11 @@ var ts; visitedSymbolTablesMap.set(id, visitedSymbolTables = []); } return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols, ignoreQualification); + var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables.pop(); return result; } @@ -39303,7 +39532,7 @@ var ts; !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols, ignoreQualification) { + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (isAccessible(symbols.get(symbol.escapedName), undefined, ignoreQualification)) { return [symbol]; } @@ -39313,6 +39542,7 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 271))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification); @@ -39403,7 +39633,7 @@ var ts; return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -39622,7 +39852,7 @@ var ts; return flags & 814775659; } function isClassInstanceSide(type) { - return !!type.symbol && !!(type.symbol.flags & 32) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824)); + return !!type.symbol && !!(type.symbol.flags & 32) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288) && !!(ts.getObjectFlags(type) & 16777216))); } function createNodeBuilder() { return { @@ -40208,7 +40438,7 @@ var ts; } if (resolvedType.stringIndexInfo) { var indexSignature = void 0; - if (resolvedType.objectFlags & 2048) { + if (resolvedType.objectFlags & 1024) { indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0, context, createElidedInformationPlaceholder(context)); } else { @@ -40252,10 +40482,17 @@ var ts; } return ts.factory.createKeywordTypeNode(128); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + return !!(ts.getCheckFlags(propertySymbol) & 8192) + && (ts.contains(context.reverseMappedStack, propertySymbol) + || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0]) + && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16))); + } function addPropertyToElementList(propertySymbol, context, typeElements) { var _a; var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192); - var propertyType = propertyIsReverseMapped && context.flags & 33554432 ? + var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; @@ -40287,16 +40524,20 @@ var ts; } } else { - var savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? 33554432 : 0; var propertyTypeNode = void 0; - if (propertyIsReverseMapped && !!(savedFlags & 33554432)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } } - context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142)] : undefined; if (modifiers) { context.approximateLength += 9; @@ -40335,25 +40576,25 @@ var ts; } var mayHaveNameCollisions = !(context.flags & 64); var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; - var result_4 = []; + var result_5 = []; var i = 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result_4.push(typeNode_1); + result_5.push(typeNode_1); } break; } context.approximateLength += 2; var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result_4.push(typeNode); + result_5.push(typeNode); if (seenNames && ts.isIdentifierTypeReference(typeNode)) { - seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]); + seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]); } } } @@ -40368,13 +40609,13 @@ var ts; })) { for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var _a = types_3[_i], type = _a[0], resultIndex = _a[1]; - result_4[resultIndex] = typeToTypeNodeHelper(type, context); + result_5[resultIndex] = typeToTypeNodeHelper(type, context); } } }); context.flags = saveContextFlags; } - return result_4; + return result_5; } } function typesAreSameReference(a, b) { @@ -40676,7 +40917,7 @@ var ts; var isBundle_1 = !!ts.outFile(compilerOptions); var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map()); links.specifierCache.set(contextFile.path, specifier); } @@ -40945,12 +41186,12 @@ var ts; function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { if (type !== errorType && enclosingDeclaration) { var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) { var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); - if (result_5) { - return result_5; + var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_6) { + return result_6; } } } @@ -40967,10 +41208,14 @@ var ts; function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { if (type !== errorType && context.enclosingDeclaration) { var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); - if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) { + var annotated = getTypeFromTypeNode(annotation); + var thisInstantiated = annotated.flags & 262144 && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -42379,7 +42624,7 @@ var ts; var stringIndexInfo = getIndexInfoOfType(source, 0); var numberIndexInfo = getIndexInfoOfType(source, 1); var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= 131072; + result.objectFlags |= 8388608; return result; } function isGenericTypeWithUndefinedConstraint(type) { @@ -42635,6 +42880,21 @@ var ts; } ; } + function getFlowTypeFromCommonJSExport(symbol) { + var file = ts.getSourceFileOfNode(symbol.declarations[0]); + var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName); + var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); }); + var reference = areAllModuleExports + ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName) + : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + ts.setParent(reference.expression.expression, reference.expression); + } + ts.setParent(reference.expression, reference); + ts.setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); + } function getFlowTypeInConstructor(symbol, constructor) { var accessName = ts.startsWith(symbol.escapedName, "__#") ? ts.factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) @@ -42745,7 +43005,7 @@ var ts; mergeSymbolTable(exports, s.exports); } var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - type.objectFlags |= 16384; + type.objectFlags |= 8192; return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { @@ -42834,9 +43094,9 @@ var ts; } }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); - result.objectFlags |= (ts.getObjectFlags(type) & 16384); + result.objectFlags |= (ts.getObjectFlags(type) & 8192); if (result.symbol && result.symbol.flags & 32 && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { - result.objectFlags |= 1073741824; + result.objectFlags |= 16777216; } return result; } @@ -42882,7 +43142,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 | 1048576; + var objectFlags = 128 | 262144; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -42905,7 +43165,7 @@ var ts; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; - result.objectFlags |= 1048576; + result.objectFlags |= 262144; } return result; } @@ -42923,7 +43183,7 @@ var ts; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; - result.objectFlags |= 1048576; + result.objectFlags |= 262144; } return result; } @@ -43146,33 +43406,26 @@ var ts; if (writing === void 0) { writing = false; } var getter = ts.getDeclarationOfKind(symbol, 168); var setter = ts.getDeclarationOfKind(symbol, 169); - if (writing) { - var setterParameterType_1 = getAnnotatedAccessorType(setter); - if (setterParameterType_1) { - var flags = ts.getCheckFlags(symbol); - if (flags & 1) { - var links = getSymbolLinks(symbol); - return instantiateType(setterParameterType_1, links.mapper); - } - return setterParameterType_1; - } + var setterType = getAnnotatedAccessorType(setter); + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); } if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + var getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + if (setterType) { + return setterType; } if (getter && getter.body) { - return getReturnTypeFromBody(getter); + var returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); } if (setter) { if (!isPrivateWithinAmbient(setter)) { @@ -43188,6 +43441,13 @@ var ts; return anyType; } return undefined; + function instantiateTypeIfNeeded(type, symbol) { + if (ts.getCheckFlags(symbol) & 1) { + var links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); + } + return type; + } } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); @@ -43251,9 +43511,11 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); - links.type = targetSymbol.flags & 111551 - ? getTypeOfSymbol(targetSymbol) - : errorType; + var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), true); + links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & 111551 ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -44646,6 +44908,9 @@ var ts; } } } + function replaceIndexedAccess(instantiable, type, replacement) { + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } function getIndexInfoOfIndexSymbol(indexSymbol, indexKind) { var declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); if (!declaration) @@ -44666,8 +44931,18 @@ var ts; inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & 8388608 + && type.constraintType.type.objectType.flags & 262144 + && type.constraintType.type.indexType.flags & 262144) { + var newTypeParam = type.constraintType.type.objectType; + var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.mappedType = newMappedType; + inferredProp.constraintType = getIndexType(newTypeParam); + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -44859,7 +45134,7 @@ var ts; else if (type.objectFlags & 3) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 2048) { + else if (type.objectFlags & 1024) { resolveReverseMappedTypeMembers(type); } else if (type.objectFlags & 16) { @@ -45213,6 +45488,7 @@ var ts; return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b; var singleProp; var propSet; var indexTypes; @@ -45220,8 +45496,9 @@ var ts; var optionalFlag = isUnion ? 0 : 16777216; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var current = _a[_i]; + var mergedInstantiations = false; + for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) { + var current = _c[_i]; var type = getApparentType(current); if (!(type === errorType || type.flags & 131072)) { var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); @@ -45237,13 +45514,19 @@ var ts; singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new ts.Map(); - propSet.set(getSymbolId(singleProp), singleProp); + var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 : 0; }) === -1) { + mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - var id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new ts.Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + var id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | @@ -45261,7 +45544,7 @@ var ts; checkFlags |= 32 | (indexInfo.isReadonly ? 8 : 0); indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304)) { checkFlags |= 32; indexTypes = ts.append(indexTypes, undefinedType); } @@ -45275,7 +45558,16 @@ var ts; return undefined; } if (!propSet && !(checkFlags & 16) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + var clone_1 = createSymbolWithType(singleProp, singleProp.type); + clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent; + clone_1.containingType = containingType; + clone_1.mapper = singleProp.mapper; + return clone_1; + } + else { + return singleProp; + } } var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; @@ -45284,8 +45576,8 @@ var ts; var propTypes = []; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; - for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { - var prop = props_1[_b]; + for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { + var prop = props_1[_d]; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } @@ -45348,15 +45640,15 @@ var ts; return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; } function getReducedType(type) { - if (type.flags & 1048576 && type.objectFlags & 268435456) { + if (type.flags & 1048576 && type.objectFlags & 67108864) { return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); } else if (type.flags & 2097152) { - if (!(type.objectFlags & 268435456)) { - type.objectFlags |= 268435456 | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 : 0); + if (!(type.objectFlags & 67108864)) { + type.objectFlags |= 67108864 | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 134217728 : 0); } - return type.objectFlags & 536870912 ? neverType : type; + return type.objectFlags & 134217728 ? neverType : type; } return type; } @@ -45383,7 +45675,7 @@ var ts; return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024); } function elaborateNeverIntersection(errorInfo, type) { - if (ts.getObjectFlags(type) & 536870912) { + if (type.flags & 2097152 && ts.getObjectFlags(type) & 134217728) { var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, undefined, 536870912), symbolToString(neverProp)); @@ -45516,6 +45808,9 @@ var ts; } return false; } + function isOptionalPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && node.questionToken; + } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; @@ -45650,8 +45945,7 @@ var ts; if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) return undefined; var typeTag = ts.getJSDocTypeTag(node); - var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); @@ -45983,6 +46277,14 @@ var ts; else if (grandParent.kind === 160 && grandParent.parent.kind === 191) { inferences = ts.append(inferences, keyofConstraintType); } + else if (grandParent.kind === 191 && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 185 && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 191 && + grandParent.parent.checkType.type) { + var checkMappedType_1 = grandParent.parent.checkType; + var nodeType = getTypeFromTypeNode(checkMappedType_1.type); + inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); + } } } } @@ -46049,7 +46351,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 3670016; + return result & 917504; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -46167,10 +46469,16 @@ var ts; return errorType; } var aliasSymbol = getAliasSymbolForTypeNode(node); - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol) { + var _a; + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias); + return !!(declaration && ts.getContainingFunction(declaration)); + } function getTypeReferenceName(node) { switch (node.kind) { case 174: @@ -46256,9 +46564,13 @@ var ts; } function getConditionalFlowTypeOfType(type, node) { var constraints; + var covariant = true; while (node && !ts.isStatement(node) && node.kind !== 312) { var parent = node.parent; - if (parent.kind === 185 && node === parent.trueType) { + if (parent.kind === 161) { + covariant = !covariant; + } + if ((covariant || type.flags & 8650752) && parent.kind === 185 && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -46807,7 +47119,7 @@ var ts; if (type === wildcardType) includes |= 8388608; if (!strictNullChecks && flags & 98304) { - if (!(ts.getObjectFlags(type) & 524288)) + if (!(ts.getObjectFlags(type) & 131072)) includes |= 4194304; } else { @@ -46988,8 +47300,8 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576, reducedTypes); } } - var objectFlags = (includes & 468598819 ? 0 : 262144) | - (includes & 2097152 ? 268435456 : 0); + var objectFlags = (includes & 468598819 ? 0 : 65536) | + (includes & 2097152 ? 67108864 : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } function getUnionOrIntersectionTypePredicate(signatures, kind) { @@ -47044,7 +47356,7 @@ var ts; var typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id; + "#" + origin.type.id + "|" + getTypeListId(types); var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { @@ -47157,14 +47469,14 @@ var ts; } function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536); }); if (index < 0) { return false; } var i = index + 1; while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 262144) { + if (ts.getObjectFlags(t) & 65536) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -47188,7 +47500,7 @@ var ts; } } } - types[index] = getUnionTypeFromSortedList(result, 262144); + types[index] = getUnionTypeFromSortedList(result, 65536); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -47543,7 +47855,7 @@ var ts; if (noImplicitAny) { return false; } - if (ts.getObjectFlags(type) & 16384) { + if (ts.getObjectFlags(type) & 8192) { return true; } if (type.flags & 1048576) { @@ -47756,6 +48068,13 @@ var ts; } return !!(type.objectFlags & 8388608); } + if (type.flags & 33554432) { + if (!(type.objectFlags & 4194304)) { + type.objectFlags |= 4194304 | + (isGenericObjectType(type.substitute) || isGenericObjectType(type.baseType) ? 8388608 : 0); + } + return !!(type.objectFlags & 8388608); + } return !!(type.flags & 58982400) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type) { @@ -47766,6 +48085,13 @@ var ts; } return !!(type.objectFlags & 33554432); } + if (type.flags & 33554432) { + if (!(type.objectFlags & 16777216)) { + type.objectFlags |= 16777216 | + (isGenericIndexType(type.substitute) || isGenericIndexType(type.baseType) ? 33554432 : 0); + } + return !!(type.objectFlags & 33554432); + } return !!(type.flags & (58982400 | 4194304 | 134217728 | 268435456)) && !isPatternLiteralType(type); } function isThisTypeParameter(type) { @@ -47971,7 +48297,7 @@ var ts; var extraTypes; while (true) { var isUnwrapped = isTypicalNondistributiveConditional(root); - var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { @@ -47981,7 +48307,7 @@ var ts; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, undefined, 0); if (!checkTypeInstantiable) { - inferTypes(context.inferences, checkType, extendsType, 256 | 512); + inferTypes(context.inferences, checkType, extendsType, 512 | 1024); } combinedMapper = mapper ? combineTypeMappers(context.mapper, mapper) : context.mapper; } @@ -48213,7 +48539,7 @@ var ts; } } var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0), getIndexInfoOfType(type, 1)); - spread.objectFlags |= 128 | 1048576; + spread.objectFlags |= 128 | 262144; return spread; } } @@ -48310,7 +48636,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 | 1048576 | 1024 | objectFlags; + spread.objectFlags |= 128 | 262144 | 4194304 | objectFlags; return spread; } function isSpreadableProperty(prop) { @@ -48693,8 +49019,9 @@ var ts; outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || ts.emptyArray; - typeParameters = (target.objectFlags & 4 || target.symbol.flags & 2048) && !target.aliasTypeArguments ? - ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) : + var allDeclarations_1 = type.objectFlags & 4 ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & 4 || target.symbol.flags & 8192 || target.symbol.flags & 2048) && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) : typeParameters; links.outerTypeParameters = typeParameters; } @@ -48733,7 +49060,7 @@ var ts; return true; } } - return !!ts.forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node) { @@ -48745,6 +49072,9 @@ var ts; getTypeFromTypeNodeWorker(node) === tp; case 177: return true; + case 166: + case 165: + return (!node.type && !!node.body) || !!ts.forEachChild(node, containsReference); } return !!ts.forEachChild(node, containsReference); } @@ -48898,6 +49228,9 @@ var ts; var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; } + if (objectFlags & 1024) { + return instantiateReverseMappedType(type, mapper); + } return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; @@ -48947,6 +49280,21 @@ var ts; } return type; } + function instantiateReverseMappedType(type, mapper) { + var innerMappedType = instantiateType(type.mappedType, mapper); + if (!(ts.getObjectFlags(innerMappedType) & 32)) { + return type; + } + var innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304)) { + return type; + } + var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); + if (instantiated) { + return instantiated; + } + return type; + } function getPermissiveInstantiation(type) { return type.flags & (131068 | 3 | 131072) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -49771,7 +50119,7 @@ var ts; return false; } function isIgnoredJsxProperty(source, sourceProp) { - return ts.getObjectFlags(source) & 4096 && !isUnhyphenatedJsxName(sourceProp.escapedName); + return ts.getObjectFlags(source) & 2048 && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { while (true) { @@ -49781,6 +50129,7 @@ var ts; type.flags & 33554432 ? writing ? type.baseType : type.substitute : type.flags & 25165824 ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; @@ -50052,7 +50401,7 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1; } - reportErrorResults(originalSource, originalTarget, 0, !!(ts.getObjectFlags(originalSource) & 4096)); + reportErrorResults(originalSource, originalTarget, 0, !!(ts.getObjectFlags(originalSource) & 2048)); return 0; } var source = getNormalizedType(originalSource, false); @@ -50077,8 +50426,8 @@ var ts; if (relation === comparableRelation && !(target.flags & 131072) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); - var isPerformingExcessPropertyChecks = !(intersectionState & 2) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048); + var isPerformingExcessPropertyChecks = !(intersectionState & 2) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384); if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -50131,7 +50480,7 @@ var ts; } } if (result && !inPropertyCheck && (target.flags & 2097152 && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 && getApparentType(source).flags & 3670016 && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152); }))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 && getApparentType(source).flags & 3670016 && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288); }))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, 4); inPropertyCheck = false; @@ -50140,8 +50489,10 @@ var ts; return result; function reportErrorResults(source, target, result, isComparingJsxAttributes) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; var maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -50186,7 +50537,7 @@ var ts; if ((source.flags & 3145728) && (target.flags & 3145728)) { var sourceUnionOrIntersection = source; var targetUnionOrIntersection = target; - if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144) { + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536) { return; } var sourceSize = sourceUnionOrIntersection.types.length; @@ -50210,11 +50561,11 @@ var ts; } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & 3145728) { - var result_6 = eachTypeRelatedToSomeType(source, target); - if (result_6) { - result_6 &= eachTypeRelatedToSomeType(target, source); + var result_7 = eachTypeRelatedToSomeType(source, target); + if (result_7) { + result_7 &= eachTypeRelatedToSomeType(target, source); } - return result_6; + return result_7; } return recursiveTypeRelatedTo(source, target, false, 0); } @@ -50229,10 +50580,10 @@ var ts; } function hasExcessProperties(source, target, reportErrors) { var _a; - if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384) { + if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192) { return false; } - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; @@ -50576,21 +50927,21 @@ var ts; if (flags & 4194304) { return isRelatedTo(source.type, target.type, false); } - var result_7 = 0; + var result_8 = 0; if (flags & 8388608) { - if (result_7 = isRelatedTo(source.objectType, target.objectType, false)) { - if (result_7 &= isRelatedTo(source.indexType, target.indexType, false)) { - return result_7; + if (result_8 = isRelatedTo(source.objectType, target.objectType, false)) { + if (result_8 &= isRelatedTo(source.indexType, target.indexType, false)) { + return result_8; } } } if (flags & 16777216) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_7 = isRelatedTo(source.checkType, target.checkType, false)) { - if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, false)) { - if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { - if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { - return result_7; + if (result_8 = isRelatedTo(source.checkType, target.checkType, false)) { + if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, false)) { + if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { + if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { + return result_8; } } } @@ -50655,6 +51006,18 @@ var ts; } } else if (target.flags & 8388608) { + if (source.flags & 8388608) { + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } if (relation === assignableRelation || relation === comparableRelation) { var objectType = target.objectType; var indexType = target.indexType; @@ -50663,11 +51026,22 @@ var ts; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { var accessFlags = 2 | (baseObjectType !== objectType ? 1 : 0); var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { var template = getTemplateTypeFromMappedType(target); @@ -50732,22 +51106,13 @@ var ts; if (source.flags & 134217728) { instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - var result_8 = inferTypesFromTemplateLiteralType(source, target); - if (result_8 && ts.every(result_8, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + var result_9 = inferTypesFromTemplateLiteralType(source, target); + if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { return -1; } } if (source.flags & 8650752) { - if (source.flags & 8388608 && target.flags & 8388608) { - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - result &= isRelatedTo(source.indexType, target.indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - else { + if (!(source.flags & 8388608 && target.flags & 8388608)) { var constraint = getConstraintOfType(source); if (!constraint || (source.flags & 262144 && constraint.flags & 1)) { if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864))) { @@ -50759,7 +51124,7 @@ var ts; resetErrorInfo(saveErrorInfo); return result; } - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & 262144), undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -50771,6 +51136,16 @@ var ts; return result; } } + else if (source.flags & 134217728) { + if (!(target.flags & 134217728)) { + var baseConstraint = getBaseConstraintOfType(source); + var constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; + } + } + } else if (source.flags & 268435456) { if (target.flags & 268435456 && source.symbol === target.symbol) { if (result = isRelatedTo(source.type, target.type, reportErrors)) { @@ -50793,7 +51168,7 @@ var ts; var mapper = void 0; if (sourceParams) { var ctx = createInferenceContext(sourceParams, undefined, 0, isRelatedTo); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 | 512); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 | 1024); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } @@ -50846,7 +51221,7 @@ var ts; return 0; } if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target && - !(ts.getObjectFlags(source) & 8192 || ts.getObjectFlags(target) & 8192)) { + !(ts.getObjectFlags(source) & 4096 || ts.getObjectFlags(target) & 4096)) { var variances = getVariances(source.target); if (variances === ts.emptyArray) { return 1; @@ -50864,7 +51239,7 @@ var ts; return 0; } } - else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 && !isEmptyObjectType(source)) { + else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 && !isEmptyObjectType(source)) { return 0; } if (source.flags & (524288 | 2097152) && target.flags & 524288) { @@ -50892,14 +51267,19 @@ var ts; if (source.flags & (524288 | 2097152) && target.flags & 1048576) { var objectOnlyTarget = extractTypesOfKind(target, 524288 | 2097152 | 33554432); if (objectOnlyTarget.flags & 1048576) { - var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_9) { - return result_9; + var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_10) { + return result_10; } } } } return 0; + function countMessageChainBreadth(info) { + if (!info) + return 0; + return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0); + } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -50936,13 +51316,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_10; + var result_11; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } } @@ -51055,7 +51435,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576); - var result_11 = unionParent ? 0 : -1; + var result_12 = unionParent ? 0 : -1; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -51064,7 +51444,7 @@ var ts; if (!related) { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_11 &= related; + result_12 &= related; } else { if (related) { @@ -51072,13 +51452,13 @@ var ts; } } } - if (unionParent && !result_11 && targetIsOptional) { - result_11 = isRelatedTo(source, undefinedType); + if (unionParent && !result_12 && targetIsOptional) { + result_12 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_11 && reportErrors) { + if (unionParent && !result_12 && reportErrors) { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_11; + return result_12; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, undefined, intersectionState); @@ -51627,7 +52007,7 @@ var ts; } function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); - result.objectFlags |= 8192; + result.objectFlags |= 4096; return result; } function getAliasVariances(symbol) { @@ -51768,21 +52148,19 @@ var ts; return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } - function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isDeeplyNestedType(type, stack, depth) { if (depth >= 5) { var identity_1 = getRecursionIdentity(type); - if (identity_1) { - var count = 0; - for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= 5) { - return true; - } + var count = 0; + for (var i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity_1) { + count++; + if (count >= 5) { + return true; } } } @@ -51801,6 +52179,9 @@ var ts; return type.target; } } + if (type.flags & 262144) { + return type.symbol; + } if (type.flags & 8388608) { do { type = type.objectType; @@ -51810,7 +52191,7 @@ var ts; if (type.flags & 16777216) { return type.root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; @@ -51931,6 +52312,9 @@ var ts; 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; }); @@ -51960,12 +52344,30 @@ var ts; return isArrayType(type) ? getTypeArguments(type)[0] : undefined; } function isArrayLikeType(type) { - return isArrayType(type) || hasArrayOrReadonlyArrayBaseType(type) || !(type.flags & 98304) && isTypeAssignableTo(type, anyReadonlyArrayType); + return isArrayType(type) || !(type.flags & 98304) && isTypeAssignableTo(type, anyReadonlyArrayType); } - function hasArrayOrReadonlyArrayBaseType(type) { - return !!(ts.getObjectFlags(type) & 4) - && !!(ts.getObjectFlags(type.target) & 3) - && ts.some(getBaseTypes(type.target), isArrayType); + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(ts.getObjectFlags(type) & 4) || !(ts.getObjectFlags(type.target) & 3)) { + return undefined; + } + if (ts.getObjectFlags(type) & 33554432) { + return ts.getObjectFlags(type) & 67108864 ? type.cachedEquivalentBaseType : undefined; + } + type.objectFlags |= 33554432; + var target = type.target; + var bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; + } + var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type))); + } + type.objectFlags |= 67108864; + return type.cachedEquivalentBaseType = instantiatedBase; } function isEmptyArrayLiteralType(type) { var elementType = getElementTypeOfArrayType(type); @@ -52173,7 +52575,7 @@ var ts; function isObjectTypeWithInferableIndex(type) { return type.flags & 2097152 ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 | 2048 | 384 | 512)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 && isObjectTypeWithInferableIndex(type.source)); + !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8); @@ -52201,7 +52603,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384)) { return type; } var regularType = type.regularType; @@ -52212,7 +52614,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= resolved.objectFlags & ~32768; + regularNew.objectFlags |= resolved.objectFlags & ~16384; type.regularType = regularNew; return regularNew; } @@ -52242,7 +52644,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; - if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024)) { + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; names.set(prop.escapedName, prop); @@ -52289,14 +52691,14 @@ var ts; var stringIndexInfo = getIndexInfoOfType(type, 0); var numberIndexInfo = getIndexInfoOfType(type, 1); var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - result.objectFlags |= (ts.getObjectFlags(type) & (16384 | 2097152)); + result.objectFlags |= (ts.getObjectFlags(type) & (8192 | 524288)); return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 1572864) { + if (ts.getObjectFlags(type) & 393216) { if (context === undefined && type.widened) { return type.widened; } @@ -52327,7 +52729,7 @@ var ts; } function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 524288) { + if (ts.getObjectFlags(type) & 131072) { if (type.flags & 1048576) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -52353,7 +52755,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (ts.getObjectFlags(t) & 524288) { + if (ts.getObjectFlags(t) & 131072) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -52431,7 +52833,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); } @@ -52543,16 +52945,16 @@ var ts; } function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - if (objectFlags & 67108864) { - return !!(objectFlags & 134217728); + if (objectFlags & 1048576) { + return !!(objectFlags & 2097152); } var result = !!(type.flags & 465829888 || type.flags & 524288 && !isNonGenericTopLevelType(type) && (objectFlags & 4 && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations || - objectFlags & (32 | 131072)) || + objectFlags & (32 | 1024 | 8388608)) || type.flags & 3145728 && !(type.flags & 1024) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393) { - type.objectFlags |= 67108864 | (result ? 134217728 : 0); + type.objectFlags |= 1048576 | (result ? 2097152 : 0); } return result; } @@ -52601,7 +53003,7 @@ var ts; return type; } function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 2097152) || + return !(ts.getObjectFlags(type) & 524288) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) || isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType); } @@ -52619,14 +53021,18 @@ var ts; source.target.elementFlags; return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations); } - var reversed = createObjectType(2048 | 16, undefined); + var reversed = createObjectType(1024 | 16, undefined); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType, target, constraint) { var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); @@ -52797,7 +53203,7 @@ var ts; if (contravariant === void 0) { contravariant = false; } var bivariant = false; var propagationType; - var inferencePriority = 1024; + var inferencePriority = 2048; var allowComplexConstraintInference = true; var visited; var sourceStack; @@ -52853,8 +53259,8 @@ var ts; target = getActualTypeVariable(target); } if (target.flags & 8650752) { - if (ts.getObjectFlags(source) & 2097152 || source === nonInferrableAnyType || source === silentNeverType || - (priority & 64 && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (ts.getObjectFlags(source) & 524288 || source === nonInferrableAnyType || source === silentNeverType || + (priority & 128 && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -52879,7 +53285,7 @@ var ts; clearCachedInferences(inferences); } } - if (!(priority & 64) && target.flags & 262144 && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 128) && target.flags & 262144 && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -52915,7 +53321,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4) && target.flags & 4194304) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - inferWithPriority(empty, target.type, 128); + inferWithPriority(empty, target.type, 256); contravariant = !contravariant; } else if (source.flags & 8388608 && target.flags & 8388608) { @@ -52927,6 +53333,13 @@ var ts; inferFromTypes(source.type, target.type); } } + else if (source.flags & 33554432) { + inferFromTypes(source.baseType, target); + var oldPriority = priority; + priority |= 4; + inferFromTypes(source.substitute, target); + priority = oldPriority; + } else if (target.flags & 16777216) { invokeOnce(source, target, inferToConditionalType); } @@ -52945,7 +53358,7 @@ var ts; } else { source = getReducedType(source); - if (!(priority & 256 && source.flags & (2097152 | 465829888))) { + if (!(priority & 512 && source.flags & (2097152 | 465829888))) { var apparentSource = getApparentType(source); if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 | 2097152))) { allowComplexConstraintInference = false; @@ -52973,24 +53386,20 @@ var ts; } (visited || (visited = new ts.Map())).set(key, -1); var saveInferencePriority = inferencePriority; - inferencePriority = 1024; + inferencePriority = 2048; var saveExpandingFlags = expandingFlags; - var sourceIdentity = getRecursionIdentity(source) || source; - var targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && ts.contains(sourceStack, sourceIdentity)) + var sourceIdentity = getRecursionIdentity(source); + var targetIdentity = getRecursionIdentity(target); + if (ts.contains(sourceStack, sourceIdentity)) expandingFlags |= 1; - if (targetIdentity && ts.contains(targetStack, targetIdentity)) + if (ts.contains(targetStack, targetIdentity)) expandingFlags |= 2; if (expandingFlags !== 3) { - if (sourceIdentity) - (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) - (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) - targetStack.pop(); - if (sourceIdentity) - sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = -1; @@ -53030,7 +53439,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 512) { + if (strictFunctionTypes || priority & 1024) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -53078,7 +53487,7 @@ var ts; else { for (var i = 0; i < sources.length; i++) { var saveInferencePriority = inferencePriority; - inferencePriority = 1024; + inferencePriority = 2048; inferFromTypes(sources[i], t); if (inferencePriority === priority) matched_1[i] = true; @@ -53136,13 +53545,13 @@ var ts; if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 ? 8 : 4); + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 ? 16 : 8); } } return true; } if (constraintType.flags & 262144) { - inferWithPriority(getIndexType(source), constraintType, 16); + inferWithPriority(getIndexType(source), constraintType, 32); var extendedConstraint = getConstraintOfType(constraintType); if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) { return true; @@ -53165,7 +53574,7 @@ var ts; } else { var savePriority = priority; - priority |= contravariant ? 32 : 0; + priority |= contravariant ? 64 : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, target.flags); priority = savePriority; @@ -53274,7 +53683,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 2097152); + var skipParameters = !!(ts.getObjectFlags(source) & 524288); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -53324,7 +53733,7 @@ var ts; return !!(ts.getObjectFlags(type) & 128); } function isObjectOrArrayLiteralType(type) { - return !!(ts.getObjectFlags(type) & (128 | 65536)); + return !!(ts.getObjectFlags(type) & (128 | 32768)); } function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { @@ -53337,7 +53746,7 @@ var ts; return candidates; } function getContravariantInference(inference) { - return inference.priority & 208 ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + return inference.priority & 416 ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } function getCovariantInference(inference, signature) { var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates); @@ -53347,7 +53756,7 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - var unwidenedType = inference.priority & 208 ? + var unwidenedType = inference.priority & 416 ? getUnionType(baseCandidates, 2) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -53617,12 +54026,12 @@ var ts; } function getKeyPropertyName(unionType) { var types = unionType.types; - if (types.length < 10 || ts.getObjectFlags(unionType) & 262144) { + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536) { return undefined; } if (unionType.keyPropertyName === undefined) { var keyPropertyName = ts.forEach(types, function (t) { - return t.flags & (524288 | 2097152 | 58982400) ? + return t.flags & (524288 | 58982400) ? ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) : undefined; }); @@ -53706,7 +54115,8 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, ignoreObjects) { + if (ignoreObjects === void 0) { ignoreObjects = false; } var flags = type.flags; if (flags & 4) { return strictNullChecks ? 16317953 : 16776705; @@ -53743,7 +54153,7 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 : 7927560 : (type === falseType || type === regularFalseType) ? 12580616 : 16774920; } - if (flags & 524288) { + if (flags & 524288 && !ignoreObjects) { return ts.getObjectFlags(type) & 16 && isEmptyObjectType(type) ? strictNullChecks ? 16318463 : 16777215 : isFunctionObjectType(type) ? @@ -53766,14 +54176,15 @@ var ts; return 0; } if (flags & 465829888) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + 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); }, 0); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0); } if (flags & 2097152) { - return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t); }, 16777215); + ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068)); + return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215); } return 16777215; } @@ -53979,6 +54390,9 @@ var ts; function everyType(type, f) { return type.flags & 1048576 ? ts.every(type.types, f) : f(type); } + function everyContainedType(type, f) { + return type.flags & 3145728 ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 1048576) { var types = type.types; @@ -55098,7 +55512,16 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); + return filterType(type, function (t) { + if (!isRelated(t, candidate)) { + return true; + } + var constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } if (type.flags & 1048576) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); @@ -55178,17 +55601,20 @@ var ts; } function getTypeOfSymbolAtLocation(symbol, location) { symbol = symbol.exportSymbol || symbol; - if (location.kind === 78) { + if (location.kind === 78 || location.kind === 79) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, true); + } return getTypeOfSymbol(symbol); } function getControlFlowContainer(node) { @@ -55291,7 +55717,6 @@ var ts; } } function checkIdentifier(node, checkMode) { - var _a; var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -55377,7 +55802,7 @@ var ts; } } else if (isAlias) { - declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -55552,7 +55977,7 @@ var ts; break; case 164: case 163: - if (ts.hasSyntacticModifier(container, 32) && !(compilerOptions.target === 99 && compilerOptions.useDefineForClassFields)) { + if (ts.hasSyntacticModifier(container, 32) && !(compilerOptions.target === 99 && useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -56066,16 +56491,16 @@ var ts; } } function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0: return getTypeOfExpression(binaryExpression.left); + case 4: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case 5: - case 1: - case 6: - case 3: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } else if (!binaryExpression.left.symbol) { return getTypeOfExpression(binaryExpression.left); @@ -56094,11 +56519,11 @@ var ts; var id = lhs.expression; var parentSymbol = resolveName(id, id.escapedText, 111551, undefined, id.escapedText, true); if (parentSymbol) { - var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); - if (annotated) { + var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated_1) { var nameStr = ts.getElementOrPropertyAccessName(lhs); if (nameStr !== undefined) { - return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr); + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr); } } return undefined; @@ -56106,9 +56531,14 @@ var ts; } return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case 1: + case 6: + case 3: + var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; case 2: - case 4: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); + var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case 7: case 8: case 9: @@ -56129,7 +56559,7 @@ var ts; var symbol = resolveName(declaration.left, name, 111551, undefined, undefined, true, true); return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) { + function getContextualTypeForThisPropertyAssignment(binaryExpression) { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { @@ -56141,8 +56571,6 @@ var ts; } } } - if (kind === 2) - return undefined; var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression); if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, false))) { return undefined; @@ -56193,6 +56621,10 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { if (hasBindableName(element)) { @@ -56274,10 +56706,10 @@ var ts; return false; } function discriminateContextualTypeByObjectMembers(node, contextualType) { - return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function getApparentTypeOfContextualType(node, contextFlags) { var contextualType = ts.isObjectLiteralMethod(node) ? @@ -56354,7 +56786,7 @@ var ts; case 290: return getContextualTypeForObjectLiteralElement(parent, contextFlags); case 291: - return getApparentTypeOfContextualType(parent.parent, contextFlags); + return getContextualType(parent.parent, contextFlags); case 200: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); @@ -56704,7 +57136,7 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 | 1048576; + literalType.objectFlags |= 32768 | 262144; } return literalType; } @@ -56824,7 +57256,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 3670016; + objectFlags |= ts.getObjectFlags(type) & 917504; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096) : @@ -56938,9 +57370,9 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= objectFlags | 128 | 1048576; + result.objectFlags |= objectFlags | 128 | 262144; if (isJSObjectLiteral) { - result.objectFlags |= 16384; + result.objectFlags |= 8192; } if (patternWithComputedProperties) { result.objectFlags |= 512; @@ -57014,14 +57446,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var objectFlags = 4096; + var objectFlags = 2048; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 3670016; + objectFlags |= ts.getObjectFlags(exprType) & 917504; var attributeSymbol = createSymbol(4 | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -57093,7 +57525,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); - result.objectFlags |= objectFlags | 128 | 1048576; + result.objectFlags |= objectFlags | 128 | 262144; return result; } } @@ -57489,7 +57921,7 @@ var ts; } var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); if (!enclosingClass) { var thisParameter = void 0; @@ -57652,6 +58084,23 @@ var ts; if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); } + if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (compilerOptions.target === 99 && !useDefineForClassFields)) { + var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); + var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { + if (n === lexicalClass_1) + return "quit"; + if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); + } + } if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -57733,7 +58182,10 @@ var ts; function getFlowTypeOfAccessExpression(node, prop, propType, errorNode, checkMode) { var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind === 1 || - prop && !(prop.flags & (3 | 4 | 98304)) && !(prop.flags & 8192 && propType.flags & 1048576)) { + prop && + !(prop.flags & (3 | 4 | 98304)) + && !(prop.flags & 8192 && propType.flags & 1048576) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { @@ -57771,6 +58223,7 @@ var ts; var diagnosticMessage; var declarationName = ts.idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { @@ -57872,7 +58325,10 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + var diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : ts.Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -57883,6 +58339,11 @@ var ts; } diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) && + isEmptyObjectType(containingType); + } function typeHasStaticProperty(propName, containingType) { var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); return prop !== undefined && !!prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32); @@ -58281,7 +58742,7 @@ var ts; }); if (!inferenceContext) { applyToReturnTypes(contextualSignature, signature, function (source, target) { - inferTypes(context.inferences, source, target, 64); + inferTypes(context.inferences, source, target, 128); }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); @@ -58316,7 +58777,7 @@ var ts; getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64); + 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); @@ -58713,77 +59174,61 @@ var ts; return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args) { + var _a; + var spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - var belowArgCount = Number.NEGATIVE_INFINITY; - var aboveArgCount = Number.POSITIVE_INFINITY; - var argCount = args.length; + var maxBelow = Number.NEGATIVE_INFINITY; + var minAbove = Number.POSITIVE_INFINITY; var closestSignature; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var sig = signatures_8[_i]; - var minCount = getMinArgumentCount(sig); - var maxCount = getParameterCount(sig); - if (minCount < argCount && minCount > belowArgCount) - belowArgCount = minCount; - if (argCount < maxCount && maxCount < aboveArgCount) - aboveArgCount = maxCount; - if (minCount < min) { - min = minCount; + var minParameter = getMinArgumentCount(sig); + var maxParameter = getParameterCount(sig); + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + max = Math.max(max, maxParameter); + if (minParameter < args.length && minParameter > maxBelow) + maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) + minAbove = maxParameter; } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); - var paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var spanArray; - var related; - var error = hasRestParameter || hasSpreadArgument ? - hasRestParameter && hasSpreadArgument ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - ts.Diagnostics.Expected_0_arguments_but_got_1; - if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { - var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; - if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : - ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); - } - } - if (!hasSpreadArgument && argCount < min) { - var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } - if (hasRestParameter || hasSpreadArgument) { - spanArray = ts.factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); + var parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : ts.Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined); + return ts.addRelatedInfo(diagnostic, parameterError); } + return diagnostic; } else { - spanArray = ts.factory.createNodeArray(args.slice(max)); - } - var pos = ts.first(spanArray).pos; - var end = ts.last(spanArray).end; - if (end === pos) { - end++; + var errorSpan = ts.factory.createNodeArray(args.slice(max)); + var pos = ts.first(errorSpan).pos; + var end = ts.last(errorSpan).end; + if (end === pos) { + end++; + } + ts.setTextRangePosEnd(errorSpan, pos, end); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - ts.setTextRangePosEnd(spanArray, pos, end); - var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -59681,7 +60126,7 @@ var ts; var jsSymbol = getSymbolOfExpando(node, false); if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) { var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - jsAssignmentType.objectFlags |= 16384; + jsAssignmentType.objectFlags |= 8192; return getIntersectionType([returnType, jsAssignmentType]); } } @@ -60095,7 +60540,14 @@ var ts; } } function assignContextualParameterTypes(signature, context) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; + } + } if (context.thisParameter) { var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { @@ -60425,14 +60877,15 @@ var ts; return; } var hasExplicitReturn = func.flags & 512; + var errorNode = ts.getEffectiveReturnTypeNode(func) || func; if (type && type.flags & 131072) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -60444,7 +60897,7 @@ var ts; return; } } - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { @@ -60461,7 +60914,7 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, 0); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.objectFlags |= 2097152; + returnOnlyType.objectFlags |= 524288; return links.contextFreeType = returnOnlyType; } } @@ -62064,7 +62517,7 @@ var ts; checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasSyntacticModifier(node, 92)) { + if (ts.hasSyntacticModifier(node, 16476)) { if (!(func.kind === 167 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } @@ -62464,9 +62917,9 @@ var ts; if (classExtendsNull) { error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - var superCallShouldBeFirst = (compilerOptions.target !== 99 || !compilerOptions.useDefineForClassFields) && + var superCallShouldBeFirst = (compilerOptions.target !== 99 || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92); })); + ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476); })); if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; @@ -62510,15 +62963,18 @@ var ts; var symbol = getSymbolOfNode(node); var getter = ts.getDeclarationOfKind(symbol, 168); var setter = ts.getDeclarationOfKind(symbol, 169); - if (getter && setter) { + if (getter && setter && !(getNodeCheckFlags(getter) & 1)) { + getNodeLinks(getter).flags |= 1; var getterFlags = ts.getEffectiveModifierFlags(getter); var setterFlags = ts.getEffectiveModifierFlags(setter); if ((getterFlags & 128) !== (setterFlags & 128)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } if (((getterFlags & 16) && !(setterFlags & (16 | 8))) || ((getterFlags & 8) && !(setterFlags & 8))) { - error(node.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } var getterType = getAnnotatedAccessorType(getter); var setterType = getAnnotatedAccessorType(setter); @@ -63030,17 +63486,20 @@ var ts; case 298: return 2 | 1 | 4; case 267: - if (!ts.isEntityNameExpression(d.expression)) { + case 217: + var node_2 = d; + var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; + if (!ts.isEntityNameExpression(expression)) { return 1; } - d = d.expression; + d = expression; case 261: case 264: case 263: - var result_12 = 0; + var result_13 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); - return result_12; + ts.forEach(target.declarations, function (d) { result_13 |= getDeclarationSpaces(d); }); + return result_13; case 250: case 199: case 252: @@ -64092,10 +64551,6 @@ var ts; return; if (getFalsyFlags(type)) return; - if (getAwaitedTypeOfPromise(type)) { - errorAndMaybeSuggestAwait(condExpr, true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined, getTypeNameForErrorDisplay(type)); - return; - } var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr; var testedNode = ts.isIdentifier(location) ? location : ts.isPropertyAccessExpression(location) ? location.name @@ -64107,20 +64562,26 @@ var ts; return; } var callSignatures = getSignaturesOfType(type, 0); - if (callSignatures.length === 0) { + var isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } var testedSymbol = getSymbolAtLocation(testedNode); if (!testedSymbol) { return; } - var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + var isUsed = ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait(location, true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); + } + else { + error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) { + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { return !!ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); @@ -64155,7 +64616,7 @@ var ts; return ts.forEachChild(childNode, check); }); } - function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) { + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55) { var isUsed = ts.forEachChild(node.right, function visit(child) { if (ts.isIdentifier(child)) { @@ -65191,7 +65652,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - checkMembersForMissingOverrideModifier(node, type, typeWithThis); + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -65226,12 +65687,16 @@ var ts; checkPropertyInitialization(node); } } - function checkMembersForMissingOverrideModifier(node, type, typeWithThis) { + function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { var nodeInAmbientContext = !!(node.flags & 8388608); var baseTypeNode = ts.getEffectiveBaseTypeNode(node); var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); var _loop_24 = function (member) { + if (ts.hasAmbientModifier(member)) { + return "continue"; + } if (ts.isConstructorDeclaration(member)) { ts.forEach(member.parameters, function (param) { if (ts.isParameterPropertyDeclaration(param, member)) { @@ -65247,14 +65712,17 @@ var ts; } function checkClassMember(member, memberIsParameterProperty) { var hasOverride = ts.hasOverrideModifier(member); + var hasStatic = ts.hasStaticModifier(member); if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); if (!declaredProp) { return; } + var thisType = hasStatic ? staticType : typeWithThis; + var baseType = hasStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); var baseClassName = typeToString(baseWithThis); - var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); - var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && !baseProp && hasOverride) { error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } @@ -65265,7 +65733,7 @@ var ts; } if (!baseHasAbstract) { var diag = memberIsParameterProperty ? - ts.Diagnostics.This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; error(member, diag, baseClassName); } @@ -65385,7 +65853,7 @@ var ts; ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { + else if (useDefineForClassFields) { var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 164 && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432) @@ -66189,7 +66657,10 @@ var ts; } } function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + var illegalContextMessage = node.isExportEquals + ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { return; } var container = node.parent.kind === 298 ? node.parent : node.parent.parent; @@ -66267,10 +66738,12 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, _b = declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (var _i = 0, _b = declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } } @@ -66279,6 +66752,11 @@ var ts; links.exportsChecked = true; } } + function isDuplicatedCommonJSExport(declarations) { + return declarations + && declarations.length > 1 + && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); }); + } function checkSourceElement(node) { if (node) { var saveCurrentNode = currentNode; @@ -66503,8 +66981,11 @@ var ts; var paramTag = node.parent.parent; if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { var host_1 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_1) { - var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent); + if (host_1 || isCallbackTag) { + var lastParamDeclaration = isCallbackTag + ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) + : ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -66692,10 +67173,10 @@ var ts; } switch (location.kind) { case 298: - if (!ts.isExternalOrCommonJsModule(location)) + if (!ts.isExternalModule(location)) break; case 257: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475); + copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475); break; case 256: copySymbols(getSymbolOfNode(location).exports, meaning & 8); @@ -66741,6 +67222,15 @@ var ts; }); } } + function copyLocallyVisibleExportSymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + if (!ts.getDeclarationOfKind(symbol, 271) && !ts.getDeclarationOfKind(symbol, 270)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name) { return name.kind === 78 && @@ -66779,14 +67269,14 @@ var ts; } return node.parent.kind === 224; } - function isJSDocEntryNameReference(node) { + function getJSDocEntryNameReference(node) { while (node.parent.kind === 158) { node = node.parent; } while (node.parent.kind === 202) { node = node.parent; } - return node.parent.kind === 303; + return ts.isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node, callback) { var result; @@ -66941,13 +67431,28 @@ var ts; var meaning = name.parent.kind === 174 ? 788968 : 1920; return resolveEntityName(name, meaning, false, true); } - else if (isJSDocEntryNameReference(name)) { - var meaning = 788968 | 1920 | 111551; - return resolveEntityName(name, meaning, false, true, ts.getHostSignatureFromJSDoc(name)); - } - else if (ts.isJSDocLink(name.parent)) { + var jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || ts.isJSDocLink(name.parent)) { var meaning = 788968 | 1920 | 111551; - return resolveEntityName(name, meaning, true); + var symbol = resolveEntityName(name, meaning, false, false, ts.getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (ts.isQualifiedName(name) && ts.isIdentifier(name.left)) { + var links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, 0); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + var s = resolveEntityName(name.left, meaning, false); + if (s) { + var t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } } if (name.parent.kind === 173) { return resolveEntityName(name, 1); @@ -67122,10 +67627,10 @@ var ts; return checkDestructuringAssignment(expr, iteratedType || errorType); } if (expr.parent.kind === 289) { - var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); - var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType; - var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent); - return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex); + var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); + var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; + var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex); } var node = ts.cast(expr.parent, ts.isArrayLiteralExpression); var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType; @@ -67407,13 +67912,13 @@ var ts; !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && !!parameter.initializer && - !ts.hasSyntacticModifier(parameter, 92); + !ts.hasSyntacticModifier(parameter, 16476); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasSyntacticModifier(parameter, 92); + ts.hasSyntacticModifier(parameter, 16476); } function isOptionalUninitializedParameter(parameter) { return !!strictNullChecks && @@ -68077,11 +68582,11 @@ var ts; else if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); } - else if (flags & 32) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "override"); + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); } - if (node.kind === 161) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "override"); + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); } flags |= 16384; lastOverride = modifier; @@ -68093,7 +68598,7 @@ var ts; if (flags & 28) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (compilerOptions.noImplicitOverride && flags & 16384) { + else if (flags & 16384) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); } else if (flags & 32) { @@ -68128,9 +68633,6 @@ var ts; else if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); } - else if (compilerOptions.noImplicitOverride && flags & 16384) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "override"); - } else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } @@ -68143,6 +68645,9 @@ var ts; else if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } + else if (flags & 16384) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); + } flags |= 32; lastStatic = modifier; break; @@ -68191,7 +68696,7 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (compilerOptions.noImplicitOverride && flags & 16384) { + else if (flags & 16384) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); } else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { @@ -68233,6 +68738,9 @@ var ts; if (flags & 256 && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & 16384) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 79) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -68264,7 +68772,7 @@ var ts; if (flags & 128) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - if (compilerOptions.noImplicitOverride && flags & 16384) { + if (flags & 16384) { return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); } else if (flags & 256) { @@ -68278,10 +68786,10 @@ var ts; else if ((node.kind === 262 || node.kind === 261) && flags & 2) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 161 && (flags & 92) && ts.isBindingPattern(node.name)) { + else if (node.kind === 161 && (flags & 16476) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 161 && (flags & 92) && node.dotDotDotToken) { + else if (node.kind === 161 && (flags & 16476) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { @@ -69469,19 +69977,6 @@ var ts; return ts.isDeclarationName(name); } } - function isSomeImportDeclaration(decl) { - switch (decl.kind) { - case 263: - case 261: - case 264: - case 266: - return true; - case 78: - return decl.parent.kind === 266; - default: - return false; - } - } var JsxNames; (function (JsxNames) { JsxNames.JSX = "JSX"; @@ -73016,10 +73511,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_1 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_1, node); - ts.setCommentRange(clone_1, node); - return clone_1; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -73077,6 +73572,7 @@ var ts; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var shouldTransformPrivateElements = languageVersion < 99; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; @@ -73090,7 +73586,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === 99) { + || useDefineForClassFields && options.target === 99) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -73225,7 +73721,7 @@ var ts; return node; } } - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } @@ -73501,7 +73997,7 @@ var ts; if (ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { return languageVersion < 99; } return ts.isInitializedProperty(member) || shouldTransformPrivateElements && ts.isPrivateIdentifierClassElementDeclaration(member); @@ -73520,7 +74016,6 @@ var ts; return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration(undefined, undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; var properties = ts.getProperties(node, false, false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); @@ -73592,7 +74087,7 @@ var ts; } function transformProperty(property, receiver) { var _a; - var emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + var emitAssignment = !useDefineForClassFields; var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; @@ -73676,10 +74171,10 @@ var ts; 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; + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; } } } @@ -75485,9 +75980,9 @@ var ts; function convertJsxChildrenToChildrenPropObject(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) + var result_14 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_14 && factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("children", result_14) ]); } var result = ts.mapDefined(children, transformJsxChildToExpression); @@ -76687,7 +77182,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, member, undefined, container); var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName); var e; - if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) { var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; @@ -77267,13 +77762,13 @@ var ts; loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, true)); - loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, true)); + loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { - var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; @@ -79036,10 +79531,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); - ts.setSourceMapRange(clone_5, node); - ts.setCommentRange(clone_5, node); - return clone_5; + var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -79720,8 +80215,6 @@ var ts; context.onEmitNode = onEmitNode; context.enableSubstitution(78); context.enableSubstitution(217); - context.enableSubstitution(204); - context.enableSubstitution(206); context.enableSubstitution(215); context.enableSubstitution(216); context.enableSubstitution(290); @@ -79732,7 +80225,6 @@ var ts; var currentModuleInfo; var noSubstitution; var needUMDDynamicImportHelper; - var bindingReferenceCache; return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile || @@ -80524,80 +81016,39 @@ var ts; return substituteExpressionIdentifier(node); case 217: return substituteBinaryExpression(node); - case 204: - return substituteCallExpression(node); - case 206: - return substituteTaggedTemplateExpression(node); case 216: case 215: return substituteUnaryExpression(node); } return node; } - function getImportOrExportBindingReferenceWorker(node) { + function substituteExpressionIdentifier(node) { + var _a, _b; if (ts.getEmitFlags(node) & 4096) { var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); if (externalHelpersModuleName) { - return externalHelpersModuleName; + return factory.createPropertyAccessExpression(externalHelpersModuleName, node); } + return node; } else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if ((exportContainer === null || exportContainer === void 0 ? void 0 : exportContainer.kind) === 298) { - return exportContainer; + if (exportContainer && exportContainer.kind === 298) { + return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), node); } var importDeclaration = resolver.getReferencedImportDeclaration(node); - if (importDeclaration && (ts.isImportClause(importDeclaration) || ts.isImportSpecifier(importDeclaration))) { - return importDeclaration; - } - } - return undefined; - } - function getImportOrExportBindingReference(node, removeEntry) { - var result = bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.get(node); - if (!result && !(bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.has(node))) { - result = getImportOrExportBindingReferenceWorker(node); - if (!removeEntry) { - bindingReferenceCache || (bindingReferenceCache = new ts.Map()); - bindingReferenceCache.set(node, result); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || importDeclaration), factory.cloneNode(name)), node); + } } } - else if (removeEntry) { - bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.delete(node); - } - return result; - } - function substituteCallExpression(node) { - if (ts.isIdentifier(node.expression) && getImportOrExportBindingReference(node.expression, false)) { - return ts.isCallChain(node) ? - factory.updateCallChain(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.expression), node.expression), node.questionDotToken, undefined, node.arguments) : - factory.updateCallExpression(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.expression), node.expression), undefined, node.arguments); - } return node; } - function substituteTaggedTemplateExpression(node) { - if (ts.isIdentifier(node.tag) && getImportOrExportBindingReference(node.tag, false)) { - return factory.updateTaggedTemplateExpression(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.tag), node.tag), undefined, node.template); - } - return node; - } - function substituteExpressionIdentifier(node) { - var _a, _b; - var result = getImportOrExportBindingReference(node, true); - switch (result === null || result === void 0 ? void 0 : result.kind) { - case 78: - return factory.createPropertyAccessExpression(result, node); - case 298: - return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), node); - case 263: - return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(result.parent), factory.createIdentifier("default")), node); - case 266: - var name = result.propertyName || result.name; - return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = result.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || result), factory.cloneNode(name)), node); - default: - return node; - } - } function substituteBinaryExpression(node) { if (ts.isAssignmentOperator(node.operatorToken.kind) && ts.isIdentifier(node.left) @@ -82346,7 +82797,7 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, undefined); + var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, undefined); if (!ts.pathIsRelative(specifier)) { recordTypeReferenceDirectivesIfNecessary([specifier]); return; @@ -82989,7 +83440,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasSyntacticModifier(param, 92) || shouldStripInternal(param)) + if (!ts.hasSyntacticModifier(param, 16476) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 78) { @@ -83650,32 +84101,32 @@ var ts; } ts.transformNodes = transformNodes; ts.nullTransformationContext = { - get factory() { return ts.factory; }, - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: ts.returnUndefined, + factory: ts.factory, getCompilerOptions: function () { return ({}); }, - getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + getEmitHost: ts.notImplemented, getEmitHelperFactory: ts.notImplemented, + startLexicalEnvironment: ts.noop, + resumeLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + endLexicalEnvironment: ts.returnUndefined, setLexicalEnvironmentFlags: ts.noop, getLexicalEnvironmentFlags: function () { return 0; }, - hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + hoistFunctionDeclaration: ts.noop, addInitializationStatement: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop, - addDiagnostic: ts.noop, startBlockScope: ts.noop, endBlockScope: ts.returnUndefined, - addBlockScopedVariable: ts.noop + addBlockScopedVariable: ts.noop, + requestEmitHelper: ts.noop, + readEmitHelpers: ts.notImplemented, + enableSubstitution: ts.noop, + enableEmitNotification: ts.noop, + isSubstitutionEnabled: ts.notImplemented, + isEmitNotificationEnabled: ts.notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, + addDiagnostic: ts.noop, }; })(ts || (ts = {})); var ts; @@ -84356,7 +84807,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); var moduleKind = ts.getEmitModuleKind(printerOptions); @@ -84393,8 +84844,10 @@ var ts; var detachedCommentsInfo; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; - var _a = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _a.enter, exitComment = _a.exit; - var preprint = createPreprinter(handlers); + var lastSubstitution; + var currentParenthesizerRule; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + var parenthesizer = ts.factory.parenthesizer; var emitBinaryExpression = createEmitBinaryExpression(); reset(); return { @@ -84590,7 +85043,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - emit(preprint(hint, node)); + pipelineEmit(hint, node, undefined); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -84623,13 +85076,40 @@ var ts; function getCurrentLineMap() { return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } - function emit(node) { + function emit(node, parenthesizerRule) { if (node === undefined) return; var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - emitWithContext(node, emitWorker); + pipelineEmit(4, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); } + function emitIdentifierName(node) { + if (node === undefined) + return; + pipelineEmit(2, node, undefined); + } + function emitExpression(node, parenthesizerRule) { + if (node === undefined) + return; + pipelineEmit(1, node, parenthesizerRule); + } + function emitJsxAttributeValue(node) { + pipelineEmit(ts.isStringLiteral(node) ? 6 : 4, node); + } + function beforeEmitNode(node) { + if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728)) { + preserveSourceNewlines = false; + } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; + var pipelinePhase = getPipelinePhase(0, emitHint, node); + pipelinePhase(emitHint, node); + currentParenthesizerRule = undefined; + } function shouldEmitComments(node) { return !commentsDisabled && !ts.isSourceFile(node); } @@ -84640,446 +85120,467 @@ var ts; !ts.isUnparsedSource(node) && !ts.isUnparsedPrepend(node); } - function beforeEmitWithContext(node, shouldEmitComments, shouldEmitSourceMaps) { - onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); - var emitFlags = ts.getEmitFlags(node); - var commentRange = shouldEmitComments ? ts.getCommentRange(node) : undefined; - var sourceMapRange = shouldEmitSourceMaps ? ts.getSourceMapRange(node) : undefined; - if (preserveSourceNewlines && (emitFlags & 134217728)) { - preserveSourceNewlines = false; - } - if (commentRange) { - emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); - if (emitFlags & 2048) { - commentsDisabled = true; - } - } - if (sourceMapRange) { - if (ts.isUnparsedNode(node)) { - ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); - var parsed = getParsedSourceMap(node.parent); - if (parsed && sourceMapGenerator) { - sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); + function getPipelinePhase(phase, emitHint, node) { + switch (phase) { + case 0: + if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { + return pipelineEmitWithNotification; } - } - else { - var source = sourceMapRange.source || sourceMapSource; - if (node.kind !== 339 - && (emitFlags & 16) === 0 - && sourceMapRange.pos >= 0) { - emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + case 1: + if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } + return pipelineEmitWithSubstitution; } - if (emitFlags & 64) { - sourceMapsDisabled = true; + case 2: + if (shouldEmitComments(node)) { + return pipelineEmitWithComments; } - } + case 3: + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; + } + case 4: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase); } } - function afterEmitWithContext(node, shouldEmitComments, shouldEmitSourceMaps, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines) { - var emitFlags = ts.getEmitFlags(node); - var commentRange = shouldEmitComments ? ts.getCommentRange(node) : undefined; - var sourceMapRange = shouldEmitSourceMaps ? ts.getSourceMapRange(node) : undefined; - if (sourceMapRange) { - if (!ts.isUnparsedNode(node)) { - if (emitFlags & 64) { - sourceMapsDisabled = false; - } - if (node.kind !== 339 - && (emitFlags & 32) === 0 - && sourceMapRange.end >= 0) { - emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); - } - } + function getNextPipelinePhase(currentPhase, emitHint, node) { + return getPipelinePhase(currentPhase + 1, emitHint, node); + } + function pipelineEmitWithNotification(hint, node) { + var pipelinePhase = getNextPipelinePhase(0, hint, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + var savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); } - if (commentRange) { - if (emitFlags & 2048) { - commentsDisabled = false; - } - emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + else { + pipelineEmitWithHintWorker(hint, node); } - preserveSourceNewlines = savedPreserveSourceNewlines; onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + currentParenthesizerRule = undefined; } - function emitWithContext(node, emitCallback) { - var savedPreserveSourceNewlines = preserveSourceNewlines; - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; - var emitComments = shouldEmitComments(node); - var emitSourceMaps = shouldEmitSourceMaps(node); - beforeEmitWithContext(node, emitComments, emitSourceMaps); - emitCallback(node); - afterEmitWithContext(node, emitComments, emitSourceMaps, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines); - } - function emitWorker(node) { - switch (node.kind) { - case 8: - case 9: - return emitNumericOrBigIntLiteral(node); - case 10: - case 13: - case 14: - return emitLiteral(node, false); - case 11: - return emitJsxText(node); - case 15: - case 16: - case 17: - return emitLiteral(node, false); - case 78: - return emitIdentifier(node); - case 79: - return emitPrivateIdentifier(node); - case 158: - return emitQualifiedName(node); - case 159: - return emitComputedPropertyName(node); - case 160: - return emitTypeParameter(node); - case 161: - return emitParameter(node); - case 162: - return emitDecorator(node); - case 163: - return emitPropertySignature(node); - case 164: - return emitPropertyDeclaration(node); - case 165: - return emitMethodSignature(node); - case 166: - return emitMethodDeclaration(node); - case 167: - return emitConstructor(node); - case 168: - case 169: - return emitAccessorDeclaration(node); - case 170: - return emitCallSignature(node); - case 171: - return emitConstructSignature(node); - case 172: - return emitIndexSignature(node); - case 173: - return emitTypePredicate(node); - case 174: - return emitTypeReference(node); - case 175: - return emitFunctionType(node); - case 176: - return emitConstructorType(node); - case 177: - return emitTypeQuery(node); - case 178: - return emitTypeLiteral(node); - case 179: - return emitArrayType(node); - case 180: - return emitTupleType(node); - case 181: - return emitOptionalType(node); - case 183: - return emitUnionType(node); - case 184: - return emitIntersectionType(node); - case 185: - return emitConditionalType(node); - case 186: - return emitInferType(node); - case 187: - return emitParenthesizedType(node); - case 188: - return emitThisType(); - case 189: - return emitTypeOperator(node); - case 190: - return emitIndexedAccessType(node); - case 191: - return emitMappedType(node); - case 192: - return emitLiteralType(node); - case 193: - return emitNamedTupleMember(node); - case 194: - return emitTemplateType(node); - case 195: - return emitTemplateTypeSpan(node); - case 196: - return emitImportTypeNode(node); - case 197: - return emitObjectBindingPattern(node); - case 198: - return emitArrayBindingPattern(node); - case 199: - return emitBindingElement(node); - case 200: - return emitArrayLiteralExpression(node); - case 201: - return emitObjectLiteralExpression(node); - case 202: - return emitPropertyAccessExpression(node); - case 203: - return emitElementAccessExpression(node); - case 204: - return emitCallExpression(node); - case 205: - return emitNewExpression(node); - case 206: - return emitTaggedTemplateExpression(node); - case 207: - return emitTypeAssertionExpression(node); - case 208: - return emitParenthesizedExpression(node); - case 209: - return emitFunctionExpression(node); - case 210: - return emitArrowFunction(node); - case 211: - return emitDeleteExpression(node); - case 212: - return emitTypeOfExpression(node); - case 213: - return emitVoidExpression(node); - case 214: - return emitAwaitExpression(node); - case 215: - return emitPrefixUnaryExpression(node); - case 216: - return emitPostfixUnaryExpression(node); - case 217: - return emitBinaryExpression(node); - case 218: - return emitConditionalExpression(node); - case 219: - return emitTemplateExpression(node); - case 220: - return emitYieldExpression(node); - case 221: - return emitSpreadExpression(node); - case 222: - return emitClassExpression(node); - case 223: - return; - case 224: - return emitExpressionWithTypeArguments(node); - case 225: - return emitAsExpression(node); - case 226: - return emitNonNullExpression(node); - case 227: - return emitMetaProperty(node); - case 228: - ts.Debug.fail("SyntheticExpression should never be printed."); - break; - case 229: - return emitTemplateSpan(node); - case 230: - return emitSemicolonClassElement(); - case 231: - return emitBlock(node); - case 232: - return emitEmptyStatement(false); - case 233: - return emitVariableStatement(node); - case 234: - return emitExpressionStatement(node); - case 235: - return emitIfStatement(node); - case 236: - return emitDoStatement(node); - case 237: - return emitWhileStatement(node); - case 238: - return emitForStatement(node); - case 239: - return emitForInStatement(node); - case 240: - return emitForOfStatement(node); - case 241: - return emitContinueStatement(node); - case 242: - return emitBreakStatement(node); - case 243: - return emitReturnStatement(node); - case 244: - return emitWithStatement(node); - case 245: - return emitSwitchStatement(node); - case 246: - return emitLabeledStatement(node); - case 247: - return emitThrowStatement(node); - case 248: - return emitTryStatement(node); - case 249: - return emitDebuggerStatement(node); - case 250: - return emitVariableDeclaration(node); - case 251: - return emitVariableDeclarationList(node); - case 252: - return emitFunctionDeclaration(node); - case 253: - return emitClassDeclaration(node); - case 254: - return emitInterfaceDeclaration(node); - case 255: - return emitTypeAliasDeclaration(node); - case 256: - return emitEnumDeclaration(node); - case 257: - return emitModuleDeclaration(node); - case 258: - return emitModuleBlock(node); - case 259: - return emitCaseBlock(node); - case 260: - return emitNamespaceExportDeclaration(node); - case 261: - return emitImportEqualsDeclaration(node); - case 262: - return emitImportDeclaration(node); - case 263: - return emitImportClause(node); - case 264: - return emitNamespaceImport(node); - case 265: - return emitNamedImports(node); - case 266: - return emitImportSpecifier(node); - case 267: - return emitExportAssignment(node); - case 268: - return emitExportDeclaration(node); - case 269: - return emitNamedExports(node); - case 270: - return emitNamespaceExport(node); - case 271: - return emitExportSpecifier(node); - case 272: - return; - case 273: - return emitExternalModuleReference(node); - case 274: - return emitJsxElement(node); - case 275: - return emitJsxSelfClosingElement(node); - case 278: - return emitJsxFragment(node); - case 276: - case 279: - return emitJsxOpeningElementOrFragment(node); - case 277: - case 280: - return emitJsxClosingElementOrFragment(node); - case 281: - return emitJsxAttribute(node); - case 282: - return emitJsxAttributes(node); - case 283: - return emitJsxSpreadAttribute(node); - case 284: - return emitJsxExpression(node); - case 285: - return emitCaseClause(node); - case 286: - return emitDefaultClause(node); - case 287: - return emitHeritageClause(node); - case 288: - return emitCatchClause(node); - case 289: - return emitPropertyAssignment(node); - case 290: - return emitShorthandPropertyAssignment(node); - case 291: - return emitSpreadAssignment(node); - case 292: - return emitEnumMember(node); - case 293: - return writeUnparsedNode(node); - case 300: - case 294: - return emitUnparsedSourceOrPrepend(node); - case 295: - case 296: - return emitUnparsedTextLike(node); - case 297: - return emitUnparsedSyntheticReference(node); - case 298: - return emitSourceFile(node); - case 299: - ts.Debug.fail("Bundles should be printed using printBundle"); - break; - case 301: - ts.Debug.fail("InputFiles should not be printed"); - break; - case 302: - return emitJSDocTypeExpression(node); - case 303: - return emitJSDocNameReference(node); - case 304: - return writePunctuation("*"); - case 305: - return writePunctuation("?"); - case 306: - return emitJSDocNullableType(node); - case 307: - return emitJSDocNonNullableType(node); - case 308: - return emitJSDocOptionalType(node); - case 309: - return emitJSDocFunctionType(node); - case 182: - case 310: - return emitRestOrJSDocVariadicType(node); - case 312: - return emitJSDoc(node); - case 314: - return emitJSDocTypeLiteral(node); - case 315: - return emitJSDocSignature(node); - case 317: - case 322: - return emitJSDocSimpleTag(node); - case 318: - case 319: - return emitJSDocHeritageTag(node); - case 328: - return emitJSDocCallbackTag(node); - case 330: - case 337: - return emitJSDocPropertyLikeTag(node); - case 329: - case 331: - case 332: - case 333: - return emitJSDocSimpleTypedTag(node); - case 334: - return emitJSDocTemplateTag(node); - case 335: - return emitJSDocTypedefTag(node); - case 336: - return emitJSDocSeeTag(node); - case 338: - ts.Debug.fail("SyntaxList should not be printed"); - break; - case 339: - break; - case 340: - return emitPartiallyEmittedExpression(node); - case 341: - return emitCommaList(node); - case 342: - case 343: - break; - case 344: - ts.Debug.fail("SyntheticReferenceExpression should not be printed"); + function pipelineEmitWithHintWorker(hint, node) { + if (hint === 0) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 6) + return emitLiteral(ts.cast(node, ts.isStringLiteral), true); + if (hint === 3) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(true); + } + if (hint === 4) { + switch (node.kind) { + case 15: + case 16: + case 17: + return emitLiteral(node, false); + case 78: + return emitIdentifier(node); + case 79: + return emitPrivateIdentifier(node); + case 158: + return emitQualifiedName(node); + case 159: + return emitComputedPropertyName(node); + case 160: + return emitTypeParameter(node); + case 161: + return emitParameter(node); + case 162: + return emitDecorator(node); + case 163: + return emitPropertySignature(node); + case 164: + return emitPropertyDeclaration(node); + case 165: + return emitMethodSignature(node); + case 166: + return emitMethodDeclaration(node); + case 167: + return emitConstructor(node); + case 168: + case 169: + return emitAccessorDeclaration(node); + case 170: + return emitCallSignature(node); + case 171: + return emitConstructSignature(node); + case 172: + return emitIndexSignature(node); + case 173: + return emitTypePredicate(node); + case 174: + return emitTypeReference(node); + case 175: + return emitFunctionType(node); + case 176: + return emitConstructorType(node); + case 177: + return emitTypeQuery(node); + case 178: + return emitTypeLiteral(node); + case 179: + return emitArrayType(node); + case 180: + return emitTupleType(node); + case 181: + return emitOptionalType(node); + case 183: + return emitUnionType(node); + case 184: + return emitIntersectionType(node); + case 185: + return emitConditionalType(node); + case 186: + return emitInferType(node); + case 187: + return emitParenthesizedType(node); + case 224: + return emitExpressionWithTypeArguments(node); + case 188: + return emitThisType(); + case 189: + return emitTypeOperator(node); + case 190: + return emitIndexedAccessType(node); + case 191: + return emitMappedType(node); + case 192: + return emitLiteralType(node); + case 193: + return emitNamedTupleMember(node); + case 194: + return emitTemplateType(node); + case 195: + return emitTemplateTypeSpan(node); + case 196: + return emitImportTypeNode(node); + case 197: + return emitObjectBindingPattern(node); + case 198: + return emitArrayBindingPattern(node); + case 199: + return emitBindingElement(node); + case 229: + return emitTemplateSpan(node); + case 230: + return emitSemicolonClassElement(); + case 231: + return emitBlock(node); + case 233: + return emitVariableStatement(node); + case 232: + return emitEmptyStatement(false); + case 234: + return emitExpressionStatement(node); + case 235: + return emitIfStatement(node); + case 236: + return emitDoStatement(node); + case 237: + return emitWhileStatement(node); + case 238: + return emitForStatement(node); + case 239: + return emitForInStatement(node); + case 240: + return emitForOfStatement(node); + case 241: + return emitContinueStatement(node); + case 242: + return emitBreakStatement(node); + case 243: + return emitReturnStatement(node); + case 244: + return emitWithStatement(node); + case 245: + return emitSwitchStatement(node); + case 246: + return emitLabeledStatement(node); + case 247: + return emitThrowStatement(node); + case 248: + return emitTryStatement(node); + case 249: + return emitDebuggerStatement(node); + case 250: + return emitVariableDeclaration(node); + case 251: + return emitVariableDeclarationList(node); + case 252: + return emitFunctionDeclaration(node); + case 253: + return emitClassDeclaration(node); + case 254: + return emitInterfaceDeclaration(node); + case 255: + return emitTypeAliasDeclaration(node); + case 256: + return emitEnumDeclaration(node); + case 257: + return emitModuleDeclaration(node); + case 258: + return emitModuleBlock(node); + case 259: + return emitCaseBlock(node); + case 260: + return emitNamespaceExportDeclaration(node); + case 261: + return emitImportEqualsDeclaration(node); + case 262: + return emitImportDeclaration(node); + case 263: + return emitImportClause(node); + case 264: + return emitNamespaceImport(node); + case 270: + return emitNamespaceExport(node); + case 265: + return emitNamedImports(node); + case 266: + return emitImportSpecifier(node); + case 267: + return emitExportAssignment(node); + case 268: + return emitExportDeclaration(node); + case 269: + return emitNamedExports(node); + case 271: + return emitExportSpecifier(node); + case 272: + return; + case 273: + return emitExternalModuleReference(node); + case 11: + return emitJsxText(node); + case 276: + case 279: + return emitJsxOpeningElementOrFragment(node); + case 277: + case 280: + return emitJsxClosingElementOrFragment(node); + case 281: + return emitJsxAttribute(node); + case 282: + return emitJsxAttributes(node); + case 283: + return emitJsxSpreadAttribute(node); + case 284: + return emitJsxExpression(node); + case 285: + return emitCaseClause(node); + case 286: + return emitDefaultClause(node); + case 287: + return emitHeritageClause(node); + case 288: + return emitCatchClause(node); + case 289: + return emitPropertyAssignment(node); + case 290: + return emitShorthandPropertyAssignment(node); + case 291: + return emitSpreadAssignment(node); + case 292: + return emitEnumMember(node); + case 293: + return writeUnparsedNode(node); + case 300: + case 294: + return emitUnparsedSourceOrPrepend(node); + case 295: + case 296: + return emitUnparsedTextLike(node); + case 297: + return emitUnparsedSyntheticReference(node); + case 298: + return emitSourceFile(node); + case 299: + return ts.Debug.fail("Bundles should be printed using printBundle"); + case 301: + return ts.Debug.fail("InputFiles should not be printed"); + case 302: + return emitJSDocTypeExpression(node); + case 303: + return emitJSDocNameReference(node); + case 304: + return writePunctuation("*"); + case 305: + return writePunctuation("?"); + case 306: + return emitJSDocNullableType(node); + case 307: + return emitJSDocNonNullableType(node); + case 308: + return emitJSDocOptionalType(node); + case 309: + return emitJSDocFunctionType(node); + case 182: + case 310: + return emitRestOrJSDocVariadicType(node); + case 311: + return; + case 312: + return emitJSDoc(node); + case 314: + return emitJSDocTypeLiteral(node); + case 315: + return emitJSDocSignature(node); + case 317: + case 322: + return emitJSDocSimpleTag(node); + case 318: + case 319: + return emitJSDocHeritageTag(node); + case 320: + case 321: + return; + case 323: + case 324: + case 325: + case 326: + case 327: + return; + case 328: + return emitJSDocCallbackTag(node); + case 330: + case 337: + return emitJSDocPropertyLikeTag(node); + case 329: + case 331: + case 332: + case 333: + return emitJSDocSimpleTypedTag(node); + case 334: + return emitJSDocTemplateTag(node); + case 335: + return emitJSDocTypedefTag(node); + case 336: + return emitJSDocSeeTag(node); + case 339: + case 343: + case 342: + return; + } + if (ts.isExpression(node)) { + hint = 1; + if (substituteNode !== ts.noEmitSubstitution) { + var substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } + } + } + } + if (hint === 1) { + switch (node.kind) { + case 8: + case 9: + return emitNumericOrBigIntLiteral(node); + case 10: + case 13: + case 14: + return emitLiteral(node, false); + case 78: + return emitIdentifier(node); + case 200: + return emitArrayLiteralExpression(node); + case 201: + return emitObjectLiteralExpression(node); + case 202: + return emitPropertyAccessExpression(node); + case 203: + return emitElementAccessExpression(node); + case 204: + return emitCallExpression(node); + case 205: + return emitNewExpression(node); + case 206: + return emitTaggedTemplateExpression(node); + case 207: + return emitTypeAssertionExpression(node); + case 208: + return emitParenthesizedExpression(node); + case 209: + return emitFunctionExpression(node); + case 210: + return emitArrowFunction(node); + case 211: + return emitDeleteExpression(node); + case 212: + return emitTypeOfExpression(node); + case 213: + return emitVoidExpression(node); + case 214: + return emitAwaitExpression(node); + case 215: + return emitPrefixUnaryExpression(node); + case 216: + return emitPostfixUnaryExpression(node); + case 217: + return emitBinaryExpression(node); + case 218: + return emitConditionalExpression(node); + case 219: + return emitTemplateExpression(node); + case 220: + return emitYieldExpression(node); + case 221: + return emitSpreadElement(node); + case 222: + return emitClassExpression(node); + case 223: + return; + case 225: + return emitAsExpression(node); + case 226: + return emitNonNullExpression(node); + case 227: + return emitMetaProperty(node); + case 228: + return ts.Debug.fail("SyntheticExpression should never be printed."); + case 274: + return emitJsxElement(node); + case 275: + return emitJsxSelfClosingElement(node); + case 278: + return emitJsxFragment(node); + case 338: + return ts.Debug.fail("SyntaxList should not be printed"); + case 339: + return; + case 340: + return emitPartiallyEmittedExpression(node); + case 341: + return emitCommaList(node); + case 342: + case 343: + return; + case 344: + return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); + } } if (ts.isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); if (ts.isTokenKind(node.kind)) return writeTokenNode(node, writePunctuation); + ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); } function emitMappedTypeParameter(node) { emit(node.name); @@ -85088,6 +85589,13 @@ var ts; writeSpace(); emit(node.constraint); } + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1, hint, node); + ts.Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); + } function getHelpersFromBundledSourceFiles(bundle) { var result; if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) { @@ -85172,9 +85680,6 @@ var ts; writeStringLiteral(text); } } - function emitStringLiteralWithJsxAttributeEscape(node) { - emitLiteral(node, true); - } function emitUnparsedSourceOrPrepend(unparsed) { for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) { var text = _b[_a]; @@ -85218,7 +85723,7 @@ var ts; } function emitEntityName(node) { if (node.kind === 78) { - emit(node); + emitExpression(node); } else { emit(node); @@ -85226,7 +85731,7 @@ var ts; } function emitComputedPropertyName(node) { writePunctuation("["); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } function emitTypeParameter(node) { @@ -85256,11 +85761,11 @@ 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); + 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); } function emitDecorator(decorator) { writePunctuation("@"); - emit(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } function emitPropertySignature(node) { emitDecorators(node, node.decorators); @@ -85419,7 +85924,7 @@ var ts; writePunctuation("}"); } function emitArrayType(node) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -85442,21 +85947,21 @@ var ts; emit(node.type); } function emitOptionalType(node) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 516); + emitList(node, node.types, 516, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node) { - emitList(node, node.types, 520); + emitList(node, node.types, 520, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -85482,10 +85987,10 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -85508,7 +86013,7 @@ var ts; writeSpace(); } writePunctuation("["); - emitWithContext(node.typeParameter, emitMappedTypeParameter); + pipelineEmit(3, node.typeParameter); if (node.nameType) { writeSpace(); writeKeyword("as"); @@ -85536,7 +86041,7 @@ var ts; writePunctuation("}"); } function emitLiteralType(node) { - emit(node.literal); + emitExpression(node.literal); } function emitTemplateType(node) { emit(node.head); @@ -85575,12 +86080,12 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitArrayLiteralExpression(node) { var elements = node.elements; var preferNewLine = node.multiLine ? 65536 : 0; - emitList(node, elements, 8914 | preferNewLine); + emitExpressionList(node, elements, 8914 | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -85596,7 +86101,7 @@ var ts; } } function emitPropertyAccessExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24), node.expression.end, node.name.pos); var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); var linesAfterDot = getLinesBetweenNodes(node, token, node.name); @@ -85631,41 +86136,41 @@ var ts; } } function emitElementAccessExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(22, node.expression.end, writePunctuation, node); - emit(node.argumentExpression); + emitExpression(node.argumentExpression); emitTokenWithComment(23, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitList(node, node.arguments, 2576); + emitExpressionList(node, node.arguments, 2576, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { emitTokenWithComment(102, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitList(node, node.arguments, 18960); + emitExpressionList(node, node.arguments, 18960, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node) { - emit(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); - emit(node.template); + emitExpression(node.template); } function emitTypeAssertionExpression(node) { writePunctuation("<"); emit(node.type); writePunctuation(">"); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20, node.pos, writePunctuation, node); var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emit(node.expression); + emitExpression(node.expression, undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(21, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -85689,29 +86194,29 @@ var ts; function emitDeleteExpression(node) { emitTokenWithComment(88, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { emitTokenWithComment(111, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { emitTokenWithComment(113, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { emitTokenWithComment(130, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node) { writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emit(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node) { var operand = node.operand; @@ -85720,11 +86225,11 @@ var ts; || (node.operator === 40 && (operand.operator === 40 || operand.operator === 46))); } function emitPostfixUnaryExpression(node) { - emit(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } function createEmitBinaryExpression() { - return ts.createBinaryExpressionTrampoline(onEnter, maybeEmitExpression, onOperator, maybeEmitExpression, onExit, undefined); + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, undefined); function onEnter(node, state) { if (state) { state.stackIndex++; @@ -85734,7 +86239,12 @@ var ts; state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); - beforeEmitWithContext(node, emitComments_1, emitSourceMaps); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (emitComments_1) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); } else { state = { @@ -85749,6 +86259,9 @@ var ts; } return state; } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } function onOperator(operatorToken, _state, node) { var isCommaOperator = operatorToken.kind !== 27; var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); @@ -85759,6 +86272,9 @@ var ts; emitTrailingCommentsOfPosition(operatorToken.end, true); writeLinesAndIndent(linesAfterOperator, true); } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } function onExit(node, state) { var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); @@ -85770,15 +86286,35 @@ var ts; var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex]; var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex]; - afterEmitWithContext(node, shouldEmitComments_1, shouldEmitSourceMaps_1, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines); + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps_1) + emitSourceMapsAfterNode(node); + if (shouldEmitComments_1) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); state.stackIndex--; } } - function maybeEmitExpression(next) { - if (ts.isBinaryExpression(next)) { - return next; + function maybeEmitExpression(next, parent, side) { + var parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); + var pipelinePhase = getPipelinePhase(0, 1, next); + if (pipelinePhase === pipelineEmitWithSubstitution) { + ts.Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression)); + pipelinePhase = getNextPipelinePhase(1, 1, next); + lastSubstitution = undefined; + } + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (ts.isBinaryExpression(next)) { + return next; + } } - emit(next); + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1, next); } } function emitConditionalExpression(node) { @@ -85786,16 +86322,16 @@ var ts; var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emit(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, true); - emit(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, true); - emit(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { @@ -85805,22 +86341,22 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(124, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node) { + function emitSpreadElement(node) { emitTokenWithComment(25, node.pos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emit(node.expression); + emitExpression(node.expression, undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -85829,7 +86365,7 @@ var ts; } } function emitNonNullExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } function emitMetaProperty(node) { @@ -85838,7 +86374,7 @@ var ts; emit(node.name); } function emitTemplateSpan(node) { - emit(node.expression); + emitExpression(node.expression); emit(node.literal); } function emitBlock(node) { @@ -85863,11 +86399,8 @@ var ts; writeTrailingSemicolon(); } } - function emitEmbeddedEmptyStatement(_node) { - emitEmptyStatement(true); - } function emitExpressionStatement(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeTrailingSemicolon(); } @@ -85876,7 +86409,7 @@ var ts; var openParenPos = emitTokenWithComment(98, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { @@ -85895,7 +86428,7 @@ var ts; var openParenPos = emitTokenWithComment(114, startPos, writeKeyword, node); writeSpace(); emitTokenWithComment(20, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21, node.expression.end, writePunctuation, node); } function emitDoStatement(node) { @@ -85934,7 +86467,7 @@ var ts; writeSpace(); emitTokenWithComment(100, node.initializer.end, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -85947,7 +86480,7 @@ var ts; writeSpace(); emitTokenWithComment(157, node.initializer.end, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -85957,7 +86490,7 @@ var ts; emit(node); } else { - emit(node); + emitExpression(node); } } } @@ -86004,7 +86537,7 @@ var ts; var openParenPos = emitTokenWithComment(115, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -86012,7 +86545,7 @@ var ts; var openParenPos = emitTokenWithComment(106, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); @@ -86051,7 +86584,7 @@ var ts; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); @@ -86067,7 +86600,7 @@ var ts; writeKeyword("function"); emit(node.asteriskToken); writeSpace(); - emit(node.name); + emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } function emitSignatureAndBody(node, emitSignatureHead) { @@ -86091,7 +86624,7 @@ var ts; else { emitSignatureHead(node); writeSpace(); - emit(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -86159,7 +86692,7 @@ var ts; increaseIndent(); } else { - emitList(body, body.statements, 1, statementOffset); + emitList(body, body.statements, 1, undefined, statementOffset); } } function emitClassDeclaration(node) { @@ -86172,7 +86705,7 @@ var ts; writeKeyword("class"); if (node.name) { writeSpace(); - emit(node.name); + emitIdentifierName(node.name); } var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { @@ -86270,7 +86803,7 @@ var ts; } function emitModuleReference(node) { if (node.kind === 78) { - emit(node); + emitExpression(node); } else { emit(node); @@ -86286,7 +86819,7 @@ var ts; emitTokenWithComment(153, node.importClause.end, writeKeyword, node); writeSpace(); } - emit(node.moduleSpecifier); + emitExpression(node.moduleSpecifier); writeTrailingSemicolon(); } function emitImportClause(node) { @@ -86324,7 +86857,9 @@ var ts; emitTokenWithComment(87, nextPos, writeKeyword, node); } writeSpace(); - emit(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(62) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -86345,7 +86880,7 @@ var ts; var fromPos = node.exportClause ? node.exportClause.end : nextPos; emitTokenWithComment(153, fromPos, writeKeyword, node); writeSpace(); - emit(node.moduleSpecifier); + emitExpression(node.moduleSpecifier); } writeTrailingSemicolon(); } @@ -86389,7 +86924,7 @@ var ts; function emitExternalModuleReference(node) { writeKeyword("require"); writePunctuation("("); - emit(node.expression); + emitExpression(node.expression); writePunctuation(")"); } function emitJsxElement(node) { @@ -86438,17 +86973,13 @@ var ts; function emitJsxAttributes(node) { emitList(node, node.properties, 262656); } - function emitJsxAttributeValue(node) { - var emitCallback = ts.isStringLiteral(node) ? emitStringLiteralWithJsxAttributeEscape : emitWorker; - emitWithContext(node, emitCallback); - } function emitJsxAttribute(node) { emit(node.name); emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue); } function emitJsxSpreadAttribute(node) { writePunctuation("{..."); - emit(node.expression); + emitExpression(node.expression); writePunctuation("}"); } function hasTrailingCommentsAtPosition(pos) { @@ -86473,7 +87004,7 @@ var ts; } var end = emitTokenWithComment(18, node.pos, writePunctuation, node); emit(node.dotDotDotToken); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(19, ((_a = node.expression) === null || _a === void 0 ? void 0 : _a.end) || end, writePunctuation, node); if (isMultiline) { writer.decreaseIndent(); @@ -86482,7 +87013,7 @@ var ts; } function emitJsxTagName(node) { if (node.kind === 78) { - emit(node); + emitExpression(node); } else { emit(node); @@ -86491,7 +87022,7 @@ var ts; function emitCaseClause(node) { emitTokenWithComment(81, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { @@ -86540,7 +87071,7 @@ var ts; var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emit(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node) { emit(node.name); @@ -86548,18 +87079,18 @@ var ts; writeSpace(); writePunctuation("="); writeSpace(); - emit(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node) { if (node.expression) { emitTokenWithComment(25, node.pos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitJSDoc(node) { write("/**"); @@ -86796,14 +87327,14 @@ var ts; emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, 1, index === -1 ? statements.length : index); + emitList(node, statements, 1, undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } function emitPartiallyEmittedExpression(node) { - emit(node.expression); + emitExpression(node.expression); } function emitCommaList(node) { - emitList(node, node.elements, 528); + emitExpressionList(node, node.elements, 528, undefined); } function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) { var needsToSetSourceFile = !!sourceFile; @@ -86940,12 +87471,12 @@ var ts; emit(node); } } - function emitInitializer(node, equalCommentStartPos, container) { + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); emitTokenWithComment(62, equalCommentStartPos, writeOperator, container); writeSpace(); - emit(node); + emitExpression(node, parenthesizerRule); } } function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { @@ -86960,10 +87491,10 @@ var ts; emit(node); } } - function emitExpressionWithLeadingSpace(node) { + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { if (node) { writeSpace(); - emit(node); + emitExpression(node, parenthesizerRule); } } function emitWithTrailingSpace(node) { @@ -86981,7 +87512,7 @@ var ts; writeLine(); increaseIndent(); if (ts.isEmptyStatement(node)) { - emitWithContext(node, emitEmbeddedEmptyStatement); + pipelineEmit(5, node); } else { emit(node); @@ -86993,7 +87524,7 @@ var ts; emitList(parentNode, decorators, 2146305); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 53776); + emitList(parentNode, typeArguments, 53776, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { @@ -87054,7 +87585,13 @@ var ts; break; } } - function emitList(parentNode, children, format, start, count) { + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; @@ -87142,7 +87679,12 @@ var ts; shouldEmitInterveningComments = mayEmitInterveningComments; } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); shouldDecreaseIndentAfterEmit = false; @@ -87767,6 +88309,31 @@ var ts; } return node; } + function pipelineEmitWithComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(2, hint, node); + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 2048) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + if (emitFlags & 2048) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; @@ -88029,6 +88596,48 @@ var ts; } return node.parsedSourceMap || undefined; } + function pipelineEmitWithSourceMaps(hint, node) { + var pipelinePhase = getNextPipelinePhase(3, hint, node); + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + if (ts.isUnparsedNode(node)) { + ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); + var parsed = getParsedSourceMap(node.parent); + if (parsed && sourceMapGenerator) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); + } + } + else { + var source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 339 + && (emitFlags & 16) === 0 + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + } + if (emitFlags & 64) { + sourceMapsDisabled = true; + } + } + } + function emitSourceMapsAfterNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + if (!ts.isUnparsedNode(node)) { + if (emitFlags & 64) { + sourceMapsDisabled = false; + } + if (node.kind !== 339 + && (emitFlags & 32) === 0 + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); + } + } + } function skipSourceTrivia(source, pos) { return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos); } @@ -88099,653 +88708,6 @@ var ts; } } ts.createPrinter = createPrinter; - function createPreprinter(handlers) { - var _a = handlers.substituteNode, substituteNode = _a === void 0 ? ts.noEmitSubstitution : _a, _b = handlers.onEmitNode, onEmitNode = _b === void 0 ? ts.noEmitNotification : _b, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled; - var pipelineResult; - var visit = makeVisitor(pipelineVisitorForUnspecified); - var visitSourceFile = makeVisitor(pipelineVisitorForSourceFile, ts.isSourceFile); - var visitIdentifierName = makeVisitor(pipelineVisitorForIdentifierName, ts.isIdentifier); - var visitModuleName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isModuleName); - var visitPropertyName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isPropertyName); - var visitMemberName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isMemberName); - var visitBindingName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isBindingName); - var visitEntityName = makeVisitor(pipelineVisitorForIdentifierReferenceOrUnspecified, ts.isEntityName); - var visitExpression = makeVisitor(pipelineVisitorForExpression, ts.isExpression); - var visitForInitializer = makeVisitor(pipelineVisitorForForInitializer, ts.isForInitializer); - var visitTypeNode = makeVisitor(pipelineVisitorForUnspecified, ts.isTypeNode); - var visitEmbeddedStatement = makeVisitor(pipelineVisitorForEmbeddedStatement, ts.isStatement, ts.factory.liftToBlock); - var visitJsxAttributeValue = makeVisitor(pipelineVisitorForJsxAttributeValue, ts.isStringLiteralOrJsxExpression); - var visitMappedTypeParameter = makeVisitor(pipelineVisitorForMappedTypeParameter, ts.isTypeParameterDeclaration); - var visitConciseBody = makeVisitor(pipelineVisitorForConciseBody, ts.isConciseBody); - var visitFunctionBody = makeVisitor(pipelineVisitorForUnspecified, ts.isFunctionBody); - var visitList = makeListVisitor(pipelineVisitorForUnspecified); - var visitTypeNodeList = makeListVisitor(pipelineVisitorForUnspecified, ts.isTypeNode); - var visitExpressionList = makeListVisitor(pipelineVisitorForExpression, ts.isExpression); - var visitParameterList = makeListVisitor(pipelineVisitorForUnspecified, ts.isParameter); - function makeVisitor(outerVisitor, defaultTest, lift) { - function visit(node, test) { - return ts.visitNode(node, outerVisitor, test || defaultTest, lift); - } - return visit; - } - function makeListVisitor(outerVisitor, defaultTest) { - function visitList(nodes, test) { - if (test === void 0) { test = defaultTest || ts.returnTrue; } - return ts.visitNodes(nodes, outerVisitor, test); - } - return visitList; - } - function pipelineVisitorForSourceFile(node) { return pipelineVisitorWorker(0, node); } - function pipelineVisitorForExpression(node) { return pipelineVisitorWorker(1, node); } - function pipelineVisitorForIdentifierName(node) { return pipelineVisitorWorker(2, node); } - function pipelineVisitorForIdentifierNameOrUnspecified(node) { return pipelineVisitorWorker(ts.isIdentifier(node) ? 2 : 4, node); } - function pipelineVisitorForIdentifierReferenceOrUnspecified(node) { return pipelineVisitorWorker(ts.isIdentifier(node) ? 1 : 4, node); } - function pipelineVisitorForForInitializer(node) { return pipelineVisitorWorker(ts.isVariableDeclarationList(node) ? 4 : 1, node); } - function pipelineVisitorForMappedTypeParameter(node) { return pipelineVisitorWorker(3, node); } - function pipelineVisitorForEmbeddedStatement(node) { return pipelineVisitorWorker(ts.isEmptyStatement(node) ? 5 : 4, node); } - function pipelineVisitorForJsxAttributeValue(node) { return pipelineVisitorWorker(ts.isStringLiteral(node) ? 6 : 4, node); } - function pipelineVisitorForConciseBody(node) { return pipelineVisitorWorker(ts.isBlock(node) ? 4 : 1, node); } - function pipelineVisitorForUnspecified(node) { return pipelineVisitorWorker(4, node); } - function pipelineVisitorWorker(hint, node) { - resetPipelineResult(); - var pipelinePhase = getPipelinePhase(0, node); - if (pipelinePhase === pipelineVisitDirect) { - return visitor(hint, node); - } - if (pipelinePhase === pipelineVisitWithSubstitution) { - return visitor(hint, substituteNode(hint, node)); - } - pipelinePhase(hint, node); - ts.Debug.assertIsDefined(pipelineResult); - var result = pipelineResult; - resetPipelineResult(); - return result; - } - function resetPipelineResult() { - pipelineResult = undefined; - } - function getPipelinePhase(phase, node) { - switch (phase) { - case 0: - if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { - return pipelineVisitWithNotification; - } - case 1: - if (substituteNode !== ts.noEmitSubstitution) { - return pipelineVisitWithSubstitution; - } - default: - return pipelineVisitDirect; - } - } - function pipelineVisitWithNotification(hint, node) { - onEmitNode(hint, node, getPipelinePhase(1, node)); - } - function pipelineVisitWithSubstitution(hint, node) { - pipelineResult = visitor(hint, substituteNode(hint, node)); - } - function pipelineVisitDirect(hint, node) { - pipelineResult = visitor(hint, node); - } - function visitor(hint, node) { - if (hint === 0) - return preprintSourceFile(ts.cast(node, ts.isSourceFile)); - if (hint === 2) - return preprintIdentifier(ts.cast(node, ts.isIdentifier)); - if (hint === 6) - return ts.cast(node, ts.isStringLiteral); - if (hint === 3) - return preprintTypeParameterDeclaration(ts.cast(node, ts.isTypeParameterDeclaration)); - if (hint === 5) - return ts.cast(node, ts.isEmptyStatement); - var kind = node.kind; - if ((kind > 0 && kind <= 157) || kind === 188) { - return node; - } - if (hint === 4) { - if (ts.isKeyword(node.kind)) - return node; - switch (node.kind) { - case 78: - return preprintIdentifier(node); - case 158: - ts.Debug.type(node); - return ts.factory.updateQualifiedName(node, visitEntityName(node.left), visitIdentifierName(node.right)); - case 159: - ts.Debug.type(node); - return ts.factory.updateComputedPropertyName(node, visitExpression(node.expression)); - case 160: - return preprintTypeParameterDeclaration(node); - case 161: - ts.Debug.type(node); - return ts.factory.updateParameterDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.dotDotDotToken, ts.isDotDotDotToken), visitBindingName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 162: - ts.Debug.type(node); - return ts.factory.updateDecorator(node, visitExpression(node.expression)); - case 163: - ts.Debug.type(node); - return ts.factory.updatePropertySignature(node, visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type)); - case 164: - ts.Debug.type(node); - return ts.factory.updatePropertyDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken || node.exclamationToken, ts.isQuestionOrExclamationToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 165: - ts.Debug.type(node); - return ts.factory.updateMethodSignature(node, visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 166: - ts.Debug.type(node); - return ts.factory.updateMethodDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 167: - ts.Debug.type(node); - return ts.factory.updateConstructorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitParameterList(node.parameters), visitFunctionBody(node.body)); - case 168: - ts.Debug.type(node); - return ts.factory.updateGetAccessorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 169: - ts.Debug.type(node); - return ts.factory.updateSetAccessorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visitParameterList(node.parameters), visitFunctionBody(node.body)); - case 170: - ts.Debug.type(node); - return ts.factory.updateCallSignature(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 171: - ts.Debug.type(node); - return ts.factory.updateConstructSignature(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 172: - ts.Debug.type(node); - return ts.factory.updateIndexSignature(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 173: - ts.Debug.type(node); - return ts.factory.updateTypePredicateNode(node, visit(node.assertsModifier, ts.isAssertsKeyword), visit(node.parameterName, ts.isIdentifierOrThisTypeNode), visitTypeNode(node.type)); - case 174: - ts.Debug.type(node); - return ts.factory.updateTypeReferenceNode(node, visitEntityName(node.typeName), visitTypeNodeList(node.typeArguments)); - case 175: - ts.Debug.type(node); - return ts.factory.updateFunctionTypeNode(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), ts.visitNodes(node.parameters, pipelineVisitorForUnspecified, ts.isParameterDeclaration), visitTypeNode(node.type)); - case 176: - ts.Debug.type(node); - return ts.factory.updateConstructorTypeNode(node, ts.visitNodes(node.modifiers, pipelineVisitorForUnspecified, ts.isModifier), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 177: - ts.Debug.type(node); - return ts.factory.updateTypeQueryNode(node, visitEntityName(node.exprName)); - case 178: - ts.Debug.type(node); - return ts.factory.updateTypeLiteralNode(node, visitList(node.members, ts.isTypeElement)); - case 179: - ts.Debug.type(node); - return ts.factory.updateArrayTypeNode(node, visitTypeNode(node.elementType)); - case 180: - ts.Debug.type(node); - return ts.factory.updateTupleTypeNode(node, visitTypeNodeList(node.elements)); - case 181: - ts.Debug.type(node); - return ts.factory.updateOptionalTypeNode(node, visitTypeNode(node.type)); - case 182: - ts.Debug.type(node); - return ts.factory.updateRestTypeNode(node, visitTypeNode(node.type)); - case 183: - ts.Debug.type(node); - return ts.factory.updateUnionTypeNode(node, visitTypeNodeList(node.types)); - case 184: - ts.Debug.type(node); - return ts.factory.updateIntersectionTypeNode(node, visitTypeNodeList(node.types)); - case 185: - ts.Debug.type(node); - return ts.factory.updateConditionalTypeNode(node, visitTypeNode(node.checkType), visitTypeNode(node.extendsType), visitTypeNode(node.trueType), visitTypeNode(node.falseType)); - case 186: - ts.Debug.type(node); - return ts.factory.updateInferTypeNode(node, visit(node.typeParameter, ts.isTypeParameterDeclaration)); - case 196: - ts.Debug.type(node); - return ts.factory.updateImportTypeNode(node, visitTypeNode(node.argument), visitEntityName(node.qualifier), visitTypeNodeList(node.typeArguments), node.isTypeOf); - case 193: - ts.Debug.type(node); - return ts.factory.updateNamedTupleMember(node, visit(node.dotDotDotToken, ts.isDotDotDotToken), visitIdentifierName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type)); - case 187: - ts.Debug.type(node); - return ts.factory.updateParenthesizedType(node, visitTypeNode(node.type)); - case 224: - ts.Debug.type(node); - return ts.factory.updateExpressionWithTypeArguments(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments)); - case 189: - ts.Debug.type(node); - return ts.factory.updateTypeOperatorNode(node, visitTypeNode(node.type)); - case 190: - ts.Debug.type(node); - return ts.factory.updateIndexedAccessTypeNode(node, visitTypeNode(node.objectType), visitTypeNode(node.indexType)); - case 191: - ts.Debug.type(node); - return ts.factory.updateMappedTypeNode(node, visit(node.readonlyToken, ts.isReadonlyKeywordOrPlusOrMinusToken), visitMappedTypeParameter(node.typeParameter), visitTypeNode(node.nameType), visit(node.questionToken, ts.isQuestionOrPlusOrMinusToken), visitTypeNode(node.type)); - case 192: - ts.Debug.type(node); - return ts.factory.updateLiteralTypeNode(node, visitExpression(node.literal, ts.isLiteralTypeLikeExpression)); - case 194: - ts.Debug.type(node); - return ts.factory.updateTemplateLiteralType(node, visit(node.head, ts.isTemplateHead), visitList(node.templateSpans, ts.isTemplateLiteralTypeSpan)); - case 195: - ts.Debug.type(node); - return ts.factory.updateTemplateLiteralTypeSpan(node, visitTypeNode(node.type), visit(node.literal, ts.isTemplateMiddleOrTemplateTail)); - case 197: - ts.Debug.type(node); - return ts.factory.updateObjectBindingPattern(node, visitList(node.elements, ts.isBindingElement)); - case 198: - ts.Debug.type(node); - return ts.factory.updateArrayBindingPattern(node, visitList(node.elements, ts.isArrayBindingElement)); - case 199: - ts.Debug.type(node); - return ts.factory.updateBindingElement(node, visit(node.dotDotDotToken, ts.isDotDotDotToken), visitPropertyName(node.propertyName), visitBindingName(node.name), visitExpression(node.initializer)); - case 229: - ts.Debug.type(node); - return ts.factory.updateTemplateSpan(node, visitExpression(node.expression), visit(node.literal, ts.isTemplateMiddleOrTemplateTail)); - case 231: - ts.Debug.type(node); - return ts.factory.updateBlock(node, visitList(node.statements, ts.isStatement)); - case 233: - ts.Debug.type(node); - return ts.factory.updateVariableStatement(node, visitList(node.modifiers, ts.isModifier), visit(node.declarationList, ts.isVariableDeclarationList)); - case 234: - ts.Debug.type(node); - return ts.factory.updateExpressionStatement(node, visitExpression(node.expression)); - case 235: - ts.Debug.type(node); - return ts.factory.updateIfStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.thenStatement), visitEmbeddedStatement(node.elseStatement)); - case 236: - ts.Debug.type(node); - return ts.factory.updateDoStatement(node, visitEmbeddedStatement(node.statement), visitExpression(node.expression)); - case 237: - ts.Debug.type(node); - return ts.factory.updateWhileStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 238: - ts.Debug.type(node); - return ts.factory.updateForStatement(node, visitForInitializer(node.initializer), visitExpression(node.condition), visitExpression(node.incrementor), visitEmbeddedStatement(node.statement)); - case 239: - ts.Debug.type(node); - return ts.factory.updateForInStatement(node, visitForInitializer(node.initializer), visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 240: - ts.Debug.type(node); - return ts.factory.updateForOfStatement(node, visit(node.awaitModifier, ts.isAwaitKeyword), visitForInitializer(node.initializer), visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 241: - ts.Debug.type(node); - return ts.factory.updateContinueStatement(node, visitIdentifierName(node.label)); - case 242: - ts.Debug.type(node); - return ts.factory.updateBreakStatement(node, visitIdentifierName(node.label)); - case 243: - ts.Debug.type(node); - return ts.factory.updateReturnStatement(node, visitExpression(node.expression)); - case 244: - ts.Debug.type(node); - return ts.factory.updateWithStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 245: - ts.Debug.type(node); - return ts.factory.updateSwitchStatement(node, visitExpression(node.expression), visit(node.caseBlock, ts.isCaseBlock)); - case 246: - ts.Debug.type(node); - return ts.factory.updateLabeledStatement(node, visitIdentifierName(node.label), visitEmbeddedStatement(node.statement)); - case 247: - ts.Debug.type(node); - return ts.factory.updateThrowStatement(node, visitExpression(node.expression)); - case 248: - ts.Debug.type(node); - return ts.factory.updateTryStatement(node, visit(node.tryBlock, ts.isBlock), visit(node.catchClause, ts.isCatchClause), visit(node.finallyBlock, ts.isBlock)); - case 250: - ts.Debug.type(node); - return ts.factory.updateVariableDeclaration(node, visitBindingName(node.name), visit(node.exclamationToken, ts.isExclamationToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 251: - ts.Debug.type(node); - return ts.factory.updateVariableDeclarationList(node, visitList(node.declarations, ts.isVariableDeclaration)); - case 252: - ts.Debug.type(node); - return ts.factory.updateFunctionDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 253: - ts.Debug.type(node); - return ts.factory.updateClassDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isClassElement)); - case 254: - ts.Debug.type(node); - return ts.factory.updateInterfaceDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isTypeElement)); - case 255: - ts.Debug.type(node); - return ts.factory.updateTypeAliasDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitTypeNode(node.type)); - case 256: - ts.Debug.type(node); - return ts.factory.updateEnumDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.members, ts.isEnumMember)); - case 257: - ts.Debug.type(node); - return ts.factory.updateModuleDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitModuleName(node.name), visit(node.body, ts.isModuleBody)); - case 258: - ts.Debug.type(node); - return ts.factory.updateModuleBlock(node, visitList(node.statements, ts.isStatement)); - case 259: - ts.Debug.type(node); - return ts.factory.updateCaseBlock(node, visitList(node.clauses, ts.isCaseOrDefaultClause)); - case 260: - ts.Debug.type(node); - return ts.factory.updateNamespaceExportDeclaration(node, visitIdentifierName(node.name)); - case 261: - ts.Debug.type(node); - return ts.factory.updateImportEqualsDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), node.isTypeOnly, visitIdentifierName(node.name), visit(node.moduleReference, ts.isModuleReference)); - case 262: - ts.Debug.type(node); - return ts.factory.updateImportDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.importClause, ts.isImportClause), visitExpression(node.moduleSpecifier)); - case 263: - ts.Debug.type(node); - return ts.factory.updateImportClause(node, node.isTypeOnly, visitIdentifierName(node.name), visit(node.namedBindings, ts.isNamedImportBindings)); - case 264: - ts.Debug.type(node); - return ts.factory.updateNamespaceImport(node, visitIdentifierName(node.name)); - case 270: - ts.Debug.type(node); - return ts.factory.updateNamespaceExport(node, visitIdentifierName(node.name)); - case 265: - ts.Debug.type(node); - return ts.factory.updateNamedImports(node, visitList(node.elements, ts.isImportSpecifier)); - case 266: - ts.Debug.type(node); - return ts.factory.updateImportSpecifier(node, visitIdentifierName(node.propertyName), visitIdentifierName(node.name)); - case 267: - ts.Debug.type(node); - return ts.factory.updateExportAssignment(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitExpression(node.expression)); - case 268: - ts.Debug.type(node); - return ts.factory.updateExportDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), node.isTypeOnly, visit(node.exportClause, ts.isNamedExportBindings), visitExpression(node.moduleSpecifier)); - case 269: - ts.Debug.type(node); - return ts.factory.updateNamedExports(node, visitList(node.elements, ts.isExportSpecifier)); - case 271: - ts.Debug.type(node); - return ts.factory.updateExportSpecifier(node, visitIdentifierName(node.propertyName), visitIdentifierName(node.name)); - case 272: - return node; - case 273: - ts.Debug.type(node); - return ts.factory.updateExternalModuleReference(node, visitExpression(node.expression)); - case 276: - ts.Debug.type(node); - return ts.factory.updateJsxOpeningElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression), visitList(node.typeArguments, ts.isTypeNode), visit(node.attributes, ts.isJsxAttributes)); - case 277: - ts.Debug.type(node); - return ts.factory.updateJsxClosingElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression)); - case 281: - ts.Debug.type(node); - return ts.factory.updateJsxAttribute(node, visitIdentifierName(node.name), visitJsxAttributeValue(node.initializer)); - case 282: - ts.Debug.type(node); - return ts.factory.updateJsxAttributes(node, visitList(node.properties, ts.isJsxAttributeLike)); - case 283: - ts.Debug.type(node); - return ts.factory.updateJsxSpreadAttribute(node, visitExpression(node.expression)); - case 284: - ts.Debug.type(node); - return ts.factory.updateJsxExpression(node, visitExpression(node.expression)); - case 285: - ts.Debug.type(node); - return ts.factory.updateCaseClause(node, visitExpression(node.expression), visitList(node.statements, ts.isStatement)); - case 286: - ts.Debug.type(node); - return ts.factory.updateDefaultClause(node, visitList(node.statements, ts.isStatement)); - case 287: - ts.Debug.type(node); - return ts.factory.updateHeritageClause(node, visitList(node.types, ts.isExpressionWithTypeArguments)); - case 288: - ts.Debug.type(node); - return ts.factory.updateCatchClause(node, visit(node.variableDeclaration, ts.isVariableDeclaration), visit(node.block, ts.isBlock)); - case 289: - ts.Debug.type(node); - return ts.factory.updatePropertyAssignment(node, visitPropertyName(node.name), visitExpression(node.initializer)); - case 290: - ts.Debug.type(node); - return ts.factory.updateShorthandPropertyAssignment(node, visitIdentifierName(node.name, ts.isIdentifier), visitExpression(node.objectAssignmentInitializer)); - case 291: - ts.Debug.type(node); - return ts.factory.updateSpreadAssignment(node, visitExpression(node.expression)); - case 292: - ts.Debug.type(node); - return ts.factory.updateEnumMember(node, visitPropertyName(node.name), visitExpression(node.initializer)); - case 302: - case 303: - case 304: - case 305: - case 306: - case 307: - case 308: - case 309: - case 310: - case 311: - case 312: - case 314: - case 315: - case 317: - case 318: - case 319: - case 320: - case 321: - case 322: - case 323: - case 324: - case 325: - case 326: - case 328: - case 329: - case 330: - case 337: - case 331: - case 332: - case 333: - case 334: - case 335: - case 336: - return node; - } - if (ts.isExpression(node)) { - hint = 1; - if (substituteNode !== ts.noEmitSubstitution) { - node = substituteNode(hint, node); - } - } - else if (ts.isSourceFile(node)) { - return preprintSourceFile(node); - } - } - if (hint === 1) { - switch (node.kind) { - case 78: - return preprintIdentifier(node); - case 200: - ts.Debug.type(node); - return ts.factory.updateArrayLiteralExpression(node, visitExpressionList(node.elements)); - case 201: - ts.Debug.type(node); - return ts.factory.updateObjectLiteralExpression(node, visitList(node.properties, ts.isObjectLiteralElementLike)); - case 202: - if (node.flags & 32) { - ts.Debug.type(node); - return ts.factory.updatePropertyAccessChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitMemberName(node.name)); - } - ts.Debug.type(node); - return ts.factory.updatePropertyAccessExpression(node, visitExpression(node.expression), visitMemberName(node.name)); - case 203: - if (node.flags & 32) { - ts.Debug.type(node); - return ts.factory.updateElementAccessChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitExpression(node.argumentExpression)); - } - ts.Debug.type(node); - return ts.factory.updateElementAccessExpression(node, visitExpression(node.expression), visitExpression(node.argumentExpression)); - case 204: - if (node.flags & 32) { - ts.Debug.type(node); - return ts.factory.updateCallChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - } - ts.Debug.type(node); - return ts.factory.updateCallExpression(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - case 205: - ts.Debug.type(node); - return ts.factory.updateNewExpression(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - case 206: - ts.Debug.type(node); - return ts.factory.updateTaggedTemplateExpression(node, visitExpression(node.tag), visitTypeNodeList(node.typeArguments), visitExpression(node.template, ts.isTemplateLiteral)); - case 207: - ts.Debug.type(node); - return ts.factory.updateTypeAssertion(node, visitTypeNode(node.type), visitExpression(node.expression)); - case 208: - ts.Debug.type(node); - return ts.factory.updateParenthesizedExpression(node, visitExpression(node.expression)); - case 209: - ts.Debug.type(node); - return ts.factory.updateFunctionExpression(node, visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 210: - ts.Debug.type(node); - return ts.factory.updateArrowFunction(node, visitList(node.modifiers, ts.isModifier), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visit(node.equalsGreaterThanToken, ts.isEqualsGreaterThanToken), visitConciseBody(node.body)); - case 211: - ts.Debug.type(node); - return ts.factory.updateDeleteExpression(node, visitExpression(node.expression)); - case 212: - ts.Debug.type(node); - return ts.factory.updateTypeOfExpression(node, visitExpression(node.expression)); - case 213: - ts.Debug.type(node); - return ts.factory.updateVoidExpression(node, visitExpression(node.expression)); - case 214: - ts.Debug.type(node); - return ts.factory.updateAwaitExpression(node, visitExpression(node.expression)); - case 215: - ts.Debug.type(node); - return ts.factory.updatePrefixUnaryExpression(node, visitExpression(node.operand)); - case 216: - ts.Debug.type(node); - return ts.factory.updatePostfixUnaryExpression(node, visitExpression(node.operand)); - case 217: - return preprintBinaryExpression(node); - case 218: - ts.Debug.type(node); - return ts.factory.updateConditionalExpression(node, visitExpression(node.condition), visit(node.questionToken, ts.isQuestionToken), visitExpression(node.whenTrue), visit(node.colonToken, ts.isColonToken), visitExpression(node.whenFalse)); - case 219: - ts.Debug.type(node); - return ts.factory.updateTemplateExpression(node, visit(node.head, ts.isTemplateHead), visitList(node.templateSpans, ts.isTemplateSpan)); - case 220: - ts.Debug.type(node); - return ts.factory.updateYieldExpression(node, visit(node.asteriskToken, ts.isAsteriskToken), visitExpression(node.expression)); - case 221: - ts.Debug.type(node); - return ts.factory.updateSpreadElement(node, visitExpression(node.expression)); - case 222: - ts.Debug.type(node); - return ts.factory.updateClassExpression(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isClassElement)); - case 225: - ts.Debug.type(node); - return ts.factory.updateAsExpression(node, visitExpression(node.expression), visitTypeNode(node.type)); - case 226: - if (node.flags & 32) { - ts.Debug.type(node); - return ts.factory.updateNonNullChain(node, visitExpression(node.expression)); - } - ts.Debug.type(node); - return ts.factory.updateNonNullExpression(node, visitExpression(node.expression)); - case 227: - ts.Debug.type(node); - return ts.factory.updateMetaProperty(node, visitIdentifierName(node.name)); - case 274: - ts.Debug.type(node); - return ts.factory.updateJsxElement(node, visit(node.openingElement, ts.isJsxOpeningElement), visitList(node.children, ts.isJsxChild), visit(node.closingElement, ts.isJsxClosingElement)); - case 275: - ts.Debug.type(node); - return ts.factory.updateJsxSelfClosingElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression), visitList(node.typeArguments, ts.isTypeNode), visit(node.attributes, ts.isJsxAttributes)); - case 278: - ts.Debug.type(node); - return ts.factory.updateJsxFragment(node, visit(node.openingFragment, ts.isJsxOpeningFragment), visitList(node.children, ts.isJsxChild), visit(node.closingFragment, ts.isJsxClosingFragment)); - case 340: - ts.Debug.type(node); - return ts.factory.updatePartiallyEmittedExpression(node, visitExpression(node.expression)); - case 341: - ts.Debug.type(node); - return ts.factory.updateCommaListExpression(node, visitExpressionList(node.elements, ts.isExpression)); - } - } - if (ts.Debug.shouldAssert(1)) { - ts.Debug.assertMissingNode(ts.forEachChild(node, ts.identity), "Expected " + ts.Debug.formatSyntaxKind(node.kind) + " to contain no children."); - } - return node; - } - function preprintSourceFile(node) { - return ts.factory.updateSourceFile(node, visitList(node.statements, ts.isStatement)); - } - function preprintIdentifier(node) { - return ts.factory.updateIdentifier(node, visitList(node.typeArguments, ts.isTypeNodeOrTypeParameterDeclaration)); - } - function preprintTypeParameterDeclaration(node) { - return ts.factory.updateTypeParameterDeclaration(node, visitIdentifierName(node.name), visitTypeNode(node.constraint), visitTypeNode(node.default)); - } - function createPreprintBinaryExpression() { - return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); - function onEnter(node, state) { - if (state) { - state.stackIndex++; - state.leftStack[state.stackIndex] = node.left; - state.operatorStack[state.stackIndex] = node.operatorToken; - state.rightStack[state.stackIndex] = node.right; - } - else { - state = { - stackIndex: 0, - leftStack: [node.left], - operatorStack: [node.operatorToken], - rightStack: [node.right], - }; - } - return state; - } - function onLeft(left, state, _node) { - return maybeVisitExpression(left, state, "left"); - } - function onOperator(operator, state, _node) { - state.operatorStack[state.stackIndex] = visit(operator, ts.isBinaryOperatorToken); - } - function onRight(right, state, _node) { - return maybeVisitExpression(right, state, "right"); - } - function onExit(node, state) { - var left = state.leftStack[state.stackIndex]; - var operator = state.operatorStack[state.stackIndex]; - var right = state.rightStack[state.stackIndex]; - if (state.stackIndex > 0) { - state.stackIndex--; - } - return ts.factory.updateBinaryExpression(node, left, operator, right); - } - function foldState(state, result, side) { - (side === "left" ? state.leftStack : state.rightStack)[state.stackIndex] = result; - return state; - } - function maybeVisitExpression(node, state, side) { - var pipelinePhase = getPipelinePhase(0, node); - if (pipelinePhase === pipelineVisitWithSubstitution) { - node = ts.cast(substituteNode(1, node), ts.isExpression); - pipelinePhase = pipelineVisitDirect; - } - if (pipelinePhase === pipelineVisitDirect && ts.isBinaryExpression(node)) { - return node; - } - else { - (side === "left" ? state.leftStack : state.rightStack)[state.stackIndex] = visitExpression(node, ts.isExpression); - } - } - } - var preprintBinaryExpression = createPreprintBinaryExpression(); - function preprint(hint, node) { - if (substituteNode === ts.noEmitSubstitution && - onEmitNode === ts.noEmitNotification) { - return node; - } - switch (hint) { - case 0: return visitSourceFile(ts.cast(node, ts.isSourceFile)); - case 1: return visitExpression(ts.cast(node, ts.isExpression)); - case 2: return visitIdentifierName(ts.cast(node, ts.isIdentifier)); - case 3: return visitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 5: return visitEmbeddedStatement(ts.cast(node, ts.isStatement)); - case 6: return visitJsxAttributeValue(ts.cast(node, ts.isStringLiteralOrJsxExpression)); - default: return visit(node); - } - } - return preprint; - } function createBracketsMap() { var brackets = []; brackets[1024] = ["{", "}"]; @@ -89831,6 +89793,7 @@ var ts; var hasEmitBlockingDiagnostics = new ts.Map(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; + var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { @@ -89844,7 +89807,7 @@ var ts; }); }; } else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } @@ -89853,7 +89816,8 @@ var ts; actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { - var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; + typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } var packageIdToSourceFile = new ts.Map(); @@ -89982,6 +89946,7 @@ var ts; } }); } + typeReferenceDirectiveResolutionCache = undefined; oldProgram = undefined; var program = { getRootFileNames: function () { return rootNames; }, @@ -90155,13 +90120,13 @@ var ts; } var oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName); if (oldSourceFile !== file && file.resolvedModules) { - var result_14 = []; + var result_15 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_14.push(resolvedModule); + result_15.push(resolvedModule); } - return result_14; + return result_15; } var unknownModuleNames; var result; @@ -91390,11 +91355,13 @@ var ts; return host.getCanonicalFileName(fileName); } function processImportedModules(file) { + var _a; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { var moduleNames = getModuleNames(file); var resolutions = resolveModuleNamesReusingOldState(moduleNames, file); ts.Debug.assert(resolutions.length === moduleNames.length); + var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options; for (var index = 0; index < moduleNames.length; index++) { var resolution = resolutions[index]; ts.setResolvedModule(file, moduleNames[index], resolution); @@ -91410,11 +91377,11 @@ var ts; } var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !ts.getAllowJSCompilerOption(options)) + && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile)) && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -92401,7 +92368,7 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos: fileInfos, @@ -93007,7 +92974,16 @@ var ts; var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - return signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; + var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); var referencedMap; if (state.referencedMap) { @@ -93054,7 +93030,7 @@ var ts; return { fileNames: fileNames, fileInfos: fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, @@ -93086,17 +93062,16 @@ var ts; return fileIdListId; } } - function convertToReusableCompilerOptions(options, relativeToBuildInfo) { - var result = {}; + function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { + var result; var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo); + 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.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { @@ -93349,6 +93324,14 @@ var ts; state.affectedFilesPendingEmitIndex = 0; } } + function toBuilderStateFileInfo(fileInfo) { + return ts.isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + ts.isString(fileInfo.signature) ? + fileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; + } + ts.toBuilderStateFileInfo = toBuilderStateFileInfo; function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { var _a; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); @@ -93356,10 +93339,10 @@ var ts; 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), fileInfo); }); + program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); var state = { fileInfos: fileInfos, - compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, referencedMap: toMapOfReferencedSet(program.referencedMap), exportedModulesMap: toMapOfReferencedSet(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]; }), @@ -93506,17 +93489,18 @@ var ts; var resolutionsWithFailedLookups = []; var resolvedFileToResolution = ts.createMultiMap(); var hasChangedAutomaticTypeDirectiveNames = false; - var failedLookupChecks = []; - var startsWithPathChecks = []; - var isInDirectoryChecks = []; + var failedLookupChecks; + var startsWithPathChecks; + var isInDirectoryChecks; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); var resolvedModuleNames = new ts.Map(); var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache); var resolvedTypeReferenceDirectives = new ts.Map(); var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives); var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; var customFailedLookupPaths = new ts.Map(); var directoryWatchesOfFailedLookups = new ts.Map(); @@ -93565,9 +93549,9 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; clearPerDirectoryResolutions(); hasChangedAutomaticTypeDirectiveNames = false; } @@ -93598,9 +93582,8 @@ var ts; isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -93623,7 +93606,7 @@ var ts; } 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), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { primaryResult.resolvedModule = resolvedModule; (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations); @@ -93632,6 +93615,9 @@ var ts; } return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } function resolveNamesWithLocalCache(_a) { var _b; var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; @@ -93714,7 +93700,7 @@ var ts; redirectedReference: redirectedReference, cache: resolvedTypeReferenceDirectives, perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, - loader: ts.resolveTypeReferenceDirective, + loader: resolveTypeReferenceDirective, getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, }); @@ -93970,7 +93956,7 @@ var ts; } function scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { if (isCreatingWatchedDirectory) { - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); } else { var updatedPath = removeIgnoredPath(fileOrDirectoryPath); @@ -93983,8 +93969,8 @@ var ts; var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -93993,27 +93979,30 @@ var ts; if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { return false; } - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { return resolution.failedLookupLocations.some(function (location) { var locationPath = resolutionHost.toPath(location); return ts.contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) || - isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, 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); })); }); } function closeTypeRootsWatch() { @@ -94178,7 +94167,7 @@ var ts; if (!baseUrl && !paths || relativePreference === 0) { return relativePath; } - var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl; + var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -94193,7 +94182,9 @@ var ts; return nonRelative; } if (relativePreference === 3) { - var projectDirectory = host.getCurrentDirectory(); + var projectDirectory = compilerOptions.configFilePath ? + ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName); var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory); var targetIsInternal = ts.startsWith(modulePath, projectDirectory); @@ -94248,9 +94239,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 links = host.getSymlinkCache ? host.getSymlinkCache() @@ -94272,10 +94263,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; } }); }); @@ -94389,7 +94380,7 @@ var ts; ts.startsWith(relativeToBaseUrl, prefix) && ts.endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } @@ -95835,12 +95826,19 @@ var ts; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); 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) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } + if (!compilerHost.resolveTypeReferenceDirectives) { + var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4); + }; + } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -95864,6 +95862,7 @@ var ts; projectErrorsReported: new ts.Map(), compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, + typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, buildOrder: undefined, readFileWithCache: function (f) { return host.readFile(f); }, projectCompilerOptions: baseCompilerOptions, @@ -96043,7 +96042,7 @@ var ts; function disableCache(state) { if (!state.cache) return; - var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache; + var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -96052,10 +96051,8 @@ var ts; compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear(); state.cache = undefined; } function clearProjectStatus(state, resolved) { @@ -96221,6 +96218,7 @@ var ts; return withProgramOrUndefined(action) || ts.emptyArray; } function createProgram() { + var _a, _b; ts.Debug.assert(program === undefined); if (state.options.dry) { reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -96238,7 +96236,8 @@ var ts; } var host = state.host, compilerHost = state.compilerHost; state.projectCompilerOptions = config.options; - updateModuleResolutionCache(state, project, config); + (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { state.builderPrograms.set(projectPath, program); @@ -96400,7 +96399,7 @@ var ts; emitBundle(writeFile, customTransformers); break; case BuildStep.BuildInvalidatedProjectOfBundle: - ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; case BuildStep.QueueReferencingProjects: @@ -96536,28 +96535,6 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache(state, proj, config) { - if (!state.moduleResolutionCache) - return; - var moduleResolutionCache = state.moduleResolutionCache; - var projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - var ref = { - sourceFile: config.options.configFile, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { var tsconfigTime = ts.getModifiedTime(state.host, configFile); if (oldestOutputFileTime < tsconfigTime) { @@ -96569,6 +96546,7 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { + var force = !!state.options.force; var newestInputFileName = undefined; var newestInputFileTime = minimumDate; var host = state.host; @@ -96580,11 +96558,13 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = ts.getModifiedTime(host, inputFile); - host.getModifiedTime(inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + var inputTime = ts.getModifiedTime(host, inputFile); + host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) { @@ -96600,28 +96580,30 @@ var ts; var missingOutputFileName; var newestDeclarationFileContentChangedTime = minimumDate; var isOutOfDateWithInputs = false; - 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 (isDeclarationFile(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + 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 (isDeclarationFile(output)) { + var outputModifiedTime = ts.getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } var pseudoUpToDate = false; @@ -96653,7 +96635,7 @@ var ts; upstreamProjectName: ref.path }; } - if (!missingOutputFileName) { + if (!force && !missingOutputFileName) { if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { continue; } @@ -96692,7 +96674,7 @@ var ts; if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -96826,7 +96808,7 @@ var ts; } } } - function build(state, project, cancellationToken, onlyReferences) { + function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -96838,7 +96820,7 @@ var ts; if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -97013,9 +96995,9 @@ var ts; function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: function (project, cancellationToken) { return build(state, project, cancellationToken); }, + build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); }, clean: function (project) { return clean(state, project); }, - buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, true); }, + buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, true); }, cleanReferences: function (project) { return clean(state, project, true); }, getNextInvalidatedProject: function (cancellationToken) { setupInitialBuild(state, cancellationToken); @@ -97101,6 +97083,9 @@ 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)); diff --git a/lib/tsserver.js b/lib/tsserver.js index 2ebe0565b4ee9..6e6e77c2f51c8 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -96,7 +96,7 @@ var ts; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-beta"; + ts.version = "4.3.1-rc"; /* @internal */ var Comparison; (function (Comparison) { @@ -2662,11 +2662,11 @@ var ts; this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : - this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" : + this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; - var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0; + var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); } }, @@ -3687,7 +3687,7 @@ var ts; }; } var reverseMappedProperties = {}; - if (objectFlags & 2048 /* ReverseMapped */) { + if (objectFlags & 1024 /* ReverseMapped */) { var reverseMappedType = type; reverseMappedProperties = { reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id, @@ -4228,7 +4228,7 @@ var ts; 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. - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 18654] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; @@ -4429,7 +4429,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; - NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -4782,6 +4781,9 @@ var ts; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags + // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check + // for a certain TypeFlags value to determine their meaning. var ObjectFlags; (function (ObjectFlags) { ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; @@ -4794,50 +4796,59 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; - ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; - ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; - ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; - ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; - ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; - ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 1024] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 2048] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 4096] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 8192] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 16384] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ArrayLiteral"] = 32768] = "ArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 262144] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; + ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 1048576] = "CouldContainTypeVariablesComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; + ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 2097152] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags"; + // Object flags that uniquely identify the kind of ObjectType /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; + ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask"; + // Flags that require TypeFlags.Object + ObjectFlags[ObjectFlags["ContainsSpread"] = 4194304] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 8388608] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone"; + // Flags that require TypeFlags.Object and ObjectFlags.Reference /* @internal */ - ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated"; /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists"; + // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; + ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; + ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; - // Object flags that uniquely identify the kind of ObjectType + ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + // Flags that require TypeFlags.Union + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 67108864] = "ContainsIntersections"; + // Flags that require TypeFlags.Intersection /* @internal */ - ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask"; + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 67108864] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 134217728] = "IsNeverIntersection"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -4911,16 +4922,17 @@ var ts; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple"; - InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType"; - InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType"; - InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint"; - InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional"; - InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType"; - InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof"; - InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict"; - InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue"; - InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination"; + InferencePriority[InferencePriority["SubstituteSource"] = 4] = "SubstituteSource"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 8] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 16] = "PartialHomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 32] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ContravariantConditional"] = 64] = "ContravariantConditional"; + InferencePriority[InferencePriority["ReturnType"] = 128] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 256] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 512] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 1024] = "AlwaysStrict"; + InferencePriority[InferencePriority["MaxValue"] = 2048] = "MaxValue"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 416] = "PriorityImpliesCombination"; InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); /* @internal */ @@ -7857,7 +7869,7 @@ var ts; A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), - An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), @@ -7883,6 +7895,7 @@ var ts; A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), @@ -7969,7 +7982,7 @@ var ts; Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."), - The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."), + The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8011,6 +8024,7 @@ var ts; The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), + Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."), 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), @@ -8259,14 +8273,13 @@ var ts; The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), - Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), @@ -8289,17 +8302,17 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), @@ -8384,7 +8397,7 @@ var ts; Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), @@ -8392,14 +8405,14 @@ var ts; _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), - A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), @@ -8461,7 +8474,7 @@ var ts; The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), - This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_2774", "This condition will always return true since this function appears to always be defined. Did you mean to call it instead?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), @@ -8488,7 +8501,7 @@ var ts; The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), - This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined_2801", "This condition will always return true since this '{0}' appears to always be defined."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), @@ -8497,6 +8510,9 @@ var ts; This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), + Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), + Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), 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}'."), @@ -8594,7 +8610,7 @@ var ts; This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), - This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_becaus_4115", "This parameter property must be rewritten as a property declaration with an 'override' modifier because it overrides a member in base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), 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."), @@ -8630,7 +8646,7 @@ var ts; Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), - Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), @@ -8643,12 +8659,14 @@ var ts; Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), - A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -8872,7 +8890,11 @@ var ts; Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), - Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -8920,6 +8942,7 @@ var ts; _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), 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."), @@ -8961,7 +8984,7 @@ var ts; Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -9001,7 +9024,7 @@ var ts; JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), @@ -9686,11 +9709,11 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; /* @internal */ - function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { - if (stopAtComments === void 0) { stopAtComments = false; } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (ts.positionIsSynthesized(pos)) { return pos; } + var canConsumeStar = false; // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -9705,6 +9728,7 @@ var ts; if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case 9 /* tab */: case 11 /* verticalTab */: @@ -9724,6 +9748,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { @@ -9735,6 +9760,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } break; @@ -9744,12 +9770,21 @@ var ts; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; case 35 /* hash */: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42 /* asterisk */: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -11800,7 +11835,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; + return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -12116,7 +12151,7 @@ var ts; if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } ts.getNameOfDeclaration = getNameOfDeclaration; /*@internal*/ @@ -12671,7 +12706,7 @@ var ts; ts.isModifierKind = isModifierKind; /* @internal */ function isParameterPropertyModifier(kind) { - return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + return !!(ts.modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */); } ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ @@ -13631,7 +13666,9 @@ var ts; } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { @@ -13884,7 +13921,9 @@ var ts; if (node.kind === 338 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ false, isInJSDoc(node)); } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -15319,6 +15358,10 @@ var ts; return node.kind === 177 /* TypeQuery */; } ts.isPartOfTypeQuery = isPartOfTypeQuery; + function isNamespaceReexportDeclaration(node) { + return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 273 /* ExternalModuleReference */; } @@ -15931,6 +15974,7 @@ var ts; parent.kind === 267 /* ExportAssignment */ || parent.kind === 164 /* PropertyDeclaration */ || parent.kind === 234 /* ExpressionStatement */ && node.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 243 /* ReturnStatement */ || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) { return parent; @@ -19131,6 +19175,10 @@ var ts; return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; + function getUseDefineForClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === 99 /* ESNext */ : compilerOptions.useDefineForClassFields; + } + ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return oldOptions !== newOptions && ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); @@ -19202,19 +19250,33 @@ var ts; } (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); } - } + }, + setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { + this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); + var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var cache = createSymlinkCache(cwd, getCanonicalFileName); - var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { - return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + var symlinks = ts.flatMap(files, function (sf) { + var pairs = sf.resolvedModules && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedModules.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) ? [res.resolvedFileName, res.originalPath] : undefined; + })); + return ts.concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] : undefined; }))); - })); + }); for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); @@ -20211,7 +20273,11 @@ var ts; var ts; (function (ts) { function createParenthesizerRules(factory) { + var binaryLeftOperandParenthesizerCache; + var binaryRightOperandParenthesizerCache; return { + getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName, @@ -20232,6 +20298,24 @@ var ts; parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType, parenthesizeTypeArguments: parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); }; + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); }; + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } /** * Determines whether the operand to a BinaryExpression needs to be parenthesized. * @@ -20560,6 +20644,8 @@ var ts; } ts.createParenthesizerRules = createParenthesizerRules; ts.nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; }, + getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; }, parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; }, parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; }, parenthesizeExpressionOfComputedPropertyName: ts.identity, @@ -21501,6 +21587,7 @@ var ts; case 155 /* BigIntKeyword */: case 141 /* NeverKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 147 /* StringKeyword */: case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: @@ -21583,15 +21670,15 @@ var ts; if (flags & 32 /* Static */) { result.push(createModifier(123 /* StaticKeyword */)); } + if (flags & 16384 /* Override */) { + result.push(createModifier(156 /* OverrideKeyword */)); + } if (flags & 64 /* Readonly */) { result.push(createModifier(142 /* ReadonlyKeyword */)); } if (flags & 256 /* Async */) { result.push(createModifier(129 /* AsyncKeyword */)); } - if (flags & 16384 /* Override */) { - result.push(createModifier(156 /* OverrideKeyword */)); - } return result; } // @@ -21663,7 +21750,7 @@ var ts; propagateChildFlags(node.questionToken); if (questionToken) node.transformFlags |= 1 /* ContainsTypeScript */; - if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */) + if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */) node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) node.transformFlags |= 512 /* ContainsES2015 */; @@ -22330,7 +22417,7 @@ var ts; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { var node = createBaseBindingLikeDeclaration(199 /* BindingElement */, /*decorators*/ undefined, - /*modifiers*/ undefined, name, initializer); + /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= @@ -29166,6 +29253,7 @@ var ts; case 324 /* JSDocPrivateTag */: case 325 /* JSDocProtectedTag */: case 326 /* JSDocReadonlyTag */: + case 321 /* JSDocDeprecatedTag */: return visitNode(cbNode, node.tagName) || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); case 340 /* PartiallyEmittedExpression */: @@ -31256,19 +31344,21 @@ var ts; function parseParameterWorker(inOuterAwaitContext) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); + // 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(); if (token() === 107 /* ThisKeyword */) { - var node_1 = factory.createParameterDeclaration( - /*decorators*/ undefined, + var node_1 = factory.createParameterDeclaration(decorators, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); + if (decorators) { + parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } return withJSDoc(finishNode(node_1, pos), hasJSDoc); } - // 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 savedTopLevel = topLevel; topLevel = false; var modifiers = parseModifiers(); @@ -33554,12 +33644,13 @@ var ts; // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var openBracePosition = scanner.getTokenPos(); if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { var multiLine = scanner.hasPrecedingLineBreak(); var statements = parseList(1 /* BlockStatements */, parseStatement); parseExpectedMatchingBrackets(18 /* OpenBraceToken */, 19 /* CloseBraceToken */, openBracePosition); - var result = finishNode(factory.createBlock(statements, multiLine), pos); + var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); if (token() === 62 /* EqualsToken */) { parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); nextToken(); @@ -33568,7 +33659,7 @@ var ts; } else { var statements = createMissingList(); - return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -33595,11 +33686,13 @@ var ts; } function parseEmptyStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(26 /* SemicolonToken */); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(98 /* IfKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); @@ -33607,10 +33700,11 @@ var ts; parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var thenStatement = parseStatement(); var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(89 /* DoKeyword */); var statement = parseStatement(); parseExpected(114 /* WhileKeyword */); @@ -33623,20 +33717,22 @@ var ts; // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. parseOptional(26 /* SemicolonToken */); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(114 /* WhileKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(96 /* ForKeyword */); var awaitToken = parseOptionalToken(130 /* AwaitKeyword */); parseExpected(20 /* OpenParenToken */); @@ -33672,34 +33768,37 @@ var ts; parseExpected(21 /* CloseParenToken */); node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(kind === 242 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); var node = kind === 242 /* BreakStatement */ ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(104 /* ReturnKeyword */); var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(115 /* WithKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { var pos = getNodePos(); @@ -33728,17 +33827,19 @@ var ts; } function parseSwitchStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(106 /* SwitchKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { // ThrowStatement[Yield] : // throw [no LineTerminator here]Expression[In, ?Yield]; var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(108 /* ThrowKeyword */); // Because of automatic semicolon insertion, we need to report error if this // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' @@ -33751,11 +33852,12 @@ var ts; expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } // TODO: Review for error recovery function parseTryStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(110 /* TryKeyword */); var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -33766,7 +33868,7 @@ var ts; parseExpected(95 /* FinallyKeyword */); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { var pos = getNodePos(); @@ -33785,9 +33887,10 @@ var ts; } function parseDebuggerStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(86 /* DebuggerKeyword */); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement() { // Avoiding having to do the lookahead for a labeled statement by just trying to parse @@ -35174,7 +35277,6 @@ var ts; state = 2 /* SavingComments */; var commentEnd = scanner.getStartPos(); var linkStart = scanner.getTextPos() - 1; - // TODO: redo here var link = parseJSDocLink(linkStart); if (link) { if (!linkEnd) { @@ -35376,8 +35478,9 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */ || !previousWhitespace && state === 2 /* SavingComments */) { - // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace + if (state === 3 /* SavingBackticks */ + || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace comments.push(scanner.getTokenText()); break; } @@ -35454,6 +35557,10 @@ var ts; return comments.join(""); } } + function isNextJSDocTokenWhitespace() { + var next = nextTokenJSDoc(); + return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */; + } function parseJSDocLink(start) { if (!tryParse(parseJSDocLinkPrefix)) { return undefined; @@ -36957,8 +37064,8 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - /* @internal */ - ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsWithoutBuild = [ + // CommandLine only options { name: "all", type: "boolean", @@ -37744,7 +37851,9 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins }, - ]); + ]; + /* @internal */ + ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsWithoutBuild); /* @internal */ ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); /* @internal */ @@ -37759,8 +37868,7 @@ var ts; ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) { return ts.hasProperty(option, "transpileOptionValue"); }); - /* @internal */ - ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsOnlyBuild = [ { name: "verbose", shortName: "v", @@ -37788,7 +37896,9 @@ var ts; description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean" } - ]); + ]; + /* @internal */ + ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsOnlyBuild); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -37842,6 +37952,10 @@ var ts; return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations)); } ts.getOptionsNameMap = getOptionsNameMap; + var compilerOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; /* @internal */ ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, @@ -37903,6 +38017,10 @@ var ts; return option.name; } function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { + var _a; + if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -38057,6 +38175,7 @@ var ts; } /*@internal*/ ts.compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -38089,7 +38208,12 @@ var ts; function getBuildOptionsNameMap() { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts)); } + var buildOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap: getOptionsNameMap + }; var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: ts.buildOpts, unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, @@ -39840,13 +39964,24 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) { var traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined; + var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -39869,6 +40004,8 @@ var ts; trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); } } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -39879,17 +40016,31 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary: primary, + resolvedFileName: resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId: packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, result); + if (traceEnabled) + traceResult(result); + return result; + function traceResult(result) { + var _a; + if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { // Check primary library paths if (typeRoots && typeRoots.length) { @@ -39919,20 +40070,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = void 0; + var result_4; if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); - result = searchResult && searchResult.value; + result_4 = searchResult && searchResult.value; } else { var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; - result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); - } - var resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); } - return resolvedFile; + return resolvedTypeScriptOnly(result_4); } else { if (traceEnabled) { @@ -39987,22 +40134,21 @@ var ts; return result; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName); - } - ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ function createCacheWithRedirects(options) { var ownMap = new ts.Map(); var redirectsMap = new ts.Map(); return { - ownMap: ownMap, + getOwnMap: getOwnMap, redirectsMap: redirectsMap, getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, clear: clear, setOwnOptions: setOwnOptions, setOwnMap: setOwnMap }; + function getOwnMap() { + return ownMap; + } function setOwnOptions(newOptions) { options = newOptions; } @@ -40028,26 +40174,88 @@ var ts; } } ts.createCacheWithRedirects = createCacheWithRedirects; - /*@internal*/ - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap }; + function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + var cache; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear }; + function getPackageJsonInfo(packageJsonPath) { + return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + if (!options.configFile) + return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + // The own map will be for projectCompilerOptions + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + // Set correct own map + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + var ref = { + sourceFile: options.configFile, + commandLine: { options: options } + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options); + } + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) { + return { + getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, + clear: clear, + update: update, + }; + function clear() { + directoryToModuleNameMap.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap); + } function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); }); } + } + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + var preDirectoryResolutionCache = 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; } }); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + packageJsonInfoCache.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); + } function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } - function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { - var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - var result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; - } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); return { get: get, set: set }; @@ -40114,7 +40322,17 @@ var ts; } } } - ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + ts.createModuleResolutionCache = createModuleResolutionCache; + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache.clear(); + } + } + ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache) { var containingDirectory = ts.getDirectoryPath(containingFile); var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -40392,7 +40610,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; 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, state.resultFromCache); function tryResolve(extensions) { @@ -40452,7 +40670,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -40485,8 +40703,9 @@ var ts; * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo" * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo" */ + /* @internal */ function parseNodeModuleFromPath(resolved) { - var path = ts.normalizePath(resolved.path); + var path = ts.normalizePath(resolved); var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; @@ -40498,6 +40717,7 @@ var ts; } return path.slice(0, indexAfterPackageName); } + ts.parseNodeModuleFromPath = parseNodeModuleFromPath; function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; @@ -40581,21 +40801,43 @@ var ts; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c; var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) + trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) + trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + var directoryExists = ts.directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = ts.readJson(packageJsonPath, host); if (traceEnabled) { trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists); // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results state.failedLookupLocations.push(packageJsonPath); } @@ -40844,7 +41086,7 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath @@ -40885,13 +41127,13 @@ var ts; * This is the minumum code needed to expose that functionality; the rest is in the host. */ /* @internal */ - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { 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 state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache); } @@ -41537,6 +41779,7 @@ var ts; } if (node.kind === 298 /* SourceFile */) { node.flags |= emitFlags; + node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -42854,9 +43097,9 @@ var ts; var saveCurrentFlow = currentFlow; for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { var typeAlias = delayedTypeAliases_1[_i]; - var host = ts.getJSDocHost(typeAlias); - container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); })) || file; - blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file; + var host = typeAlias.parent.parent; + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -43442,8 +43685,8 @@ var ts; } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + // Incorrect export assignment in some sort of block construct + bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node)); } else { var flags = ts.exportAssignmentIsAlias(node) @@ -44621,6 +44864,7 @@ var ts; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -44629,7 +44873,7 @@ var ts; var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384 /* FreshLiteral */; var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); @@ -44816,6 +45060,7 @@ var ts; return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, + getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, argumentCount) { return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */); @@ -44987,14 +45232,14 @@ var ts; var autoType = createIntrinsicType(1 /* Any */, "any"); var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); - var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */); + var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 131072 /* ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -45020,7 +45265,7 @@ var ts; var voidType = createIntrinsicType(16384 /* Void */, "void"); var neverType = createIntrinsicType(131072 /* Never */, "never"); var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -45032,7 +45277,7 @@ var ts; var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -45041,7 +45286,7 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */; + anyFunctionType.objectFlags |= 524288 /* NonInferrableType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -45703,7 +45948,7 @@ var ts; } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property - return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -45731,7 +45976,7 @@ var ts; return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); @@ -45866,7 +46111,7 @@ var ts; case 164 /* PropertyDeclaration */: // static properties in classes introduce temporary variables if (ts.hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + return target < 99 /* ESNext */ || !useDefineForClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -46251,7 +46496,7 @@ var ts; } // Perform extra checks only if error reporting was requested if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* 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. @@ -46582,8 +46827,7 @@ var ts; } } function getDeclarationOfAliasSymbol(symbol) { - var _a; - return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(isAliasSymbolDeclaration); + return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration); } /** * An alias symbol is created by one of the following declarations: @@ -46598,6 +46842,7 @@ var ts; * module.exports = * {} * {name: } + * const { x } = require ... */ function isAliasSymbolDeclaration(node) { return node.kind === 261 /* ImportEqualsDeclaration */ @@ -46828,7 +47073,7 @@ var ts; return undefined; } var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -47904,7 +48149,7 @@ var ts; var _loop_8 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } } @@ -47919,7 +48164,7 @@ var ts; // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred // to one another anyway) - if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) { + if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } break; @@ -47951,7 +48196,7 @@ var ts; if (typeof state_2 === "object") return state_2.value; } - return callback(globals); + return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace @@ -47971,11 +48216,11 @@ var ts; /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) */ - function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols, ignoreQualification); + var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables.pop(); return result; } @@ -47993,7 +48238,7 @@ var ts; !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols, ignoreQualification) { + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { // If symbol is directly available by its name in the symbol table if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; @@ -48006,6 +48251,8 @@ var ts; && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // If we're looking up a local name to reference directly, omit namespace reexports, otherwise when we're trawling through an export list to make a dotted name, we can keep it + && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */))) { @@ -48108,7 +48355,7 @@ var ts; return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -48369,7 +48616,7 @@ var ts; return flags & 814775659 /* NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { - return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */)); + return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* Object */) && !!(ts.getObjectFlags(type) & 16777216 /* IsClassInstanceClone */))); } function createNodeBuilder() { return { @@ -48982,7 +49229,7 @@ var ts; } if (resolvedType.stringIndexInfo) { var indexSignature = void 0; - if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + if (resolvedType.objectFlags & 1024 /* ReverseMapped */) { indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context)); } else { @@ -49026,10 +49273,23 @@ var ts; } return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + // Use placeholders for reverse mapped types we've either already descended into, or which + // are nested reverse mappings within a mapping over a non-anonymous type. The later is a restriction mostly just to + // reduce the blowup in printback size from doing, eg, a deep reverse mapping over `Window`. + // Since anonymous types usually come from expressions, this allows us to preserve the output + // for deep mappings which likely come from expressions, while truncating those parts which + // come from mappings over library functions. + return !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) + && (ts.contains(context.reverseMappedStack, propertySymbol) + || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0]) + && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16 /* Anonymous */))); + } function addPropertyToElementList(propertySymbol, context, typeElements) { var _a; var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */); - var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; @@ -49061,16 +49321,20 @@ var ts; } } else { - var savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; var propertyTypeNode = void 0; - if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } } - context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; @@ -49111,25 +49375,25 @@ var ts; var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); /** Map from type reference identifier text to [type, index in `result` where the type node is] */ var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; - var result_4 = []; + var result_5 = []; var i = 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result_4.push(typeNode_1); + result_5.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result_4.push(typeNode); + result_5.push(typeNode); if (seenNames && ts.isIdentifierTypeReference(typeNode)) { - seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]); + seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]); } } } @@ -49151,13 +49415,13 @@ var ts; })) { for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var _a = types_3[_i], type = _a[0], resultIndex = _a[1]; - result_4[resultIndex] = typeToTypeNodeHelper(type, context); + result_5[resultIndex] = typeToTypeNodeHelper(type, context); } } }); context.flags = saveContextFlags; } - return result_4; + return result_5; } } function typesAreSameReference(a, b) { @@ -49491,7 +49755,7 @@ var ts; // specifier preference var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map()); links.specifierCache.set(contextFile.path, specifier); } @@ -49781,13 +50045,13 @@ var ts; function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { if (type !== errorType && enclosingDeclaration) { var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) { // try to reuse the existing annotation var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); - if (result_5) { - return result_5; + var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_6) { + return result_6; } } } @@ -49804,10 +50068,14 @@ var ts; function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { if (type !== errorType && context.enclosingDeclaration) { var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); - if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) { + var annotated = getTypeFromTypeNode(annotation); + var thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -51561,7 +51829,7 @@ var ts; var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= 131072 /* ObjectRestType */; + result.objectFlags |= 8388608 /* ObjectRestType */; return result; } function isGenericTypeWithUndefinedConstraint(type) { @@ -51869,6 +52137,22 @@ var ts; } ; } + /** Create a synthetic property access flow node after the last statement of the file */ + function getFlowTypeFromCommonJSExport(symbol) { + var file = ts.getSourceFileOfNode(symbol.declarations[0]); + var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName); + var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); }); + var reference = areAllModuleExports + ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName) + : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + ts.setParent(reference.expression.expression, reference.expression); + } + ts.setParent(reference.expression, reference); + ts.setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); + } function getFlowTypeInConstructor(symbol, constructor) { var accessName = ts.startsWith(symbol.escapedName, "__#") ? ts.factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) @@ -51984,7 +52268,7 @@ var ts; mergeSymbolTable(exports, s.exports); } var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - type.objectFlags |= 16384 /* JSLiteral */; + type.objectFlags |= 8192 /* JSLiteral */; return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { @@ -52085,9 +52369,9 @@ 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.stringIndexInfo, exportedType.numberIndexInfo); - result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + result.objectFlags |= (ts.getObjectFlags(type) & 8192 /* JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { - result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type + result.objectFlags |= 16777216 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type } return result; } @@ -52146,7 +52430,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -52170,7 +52454,7 @@ var ts; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -52189,7 +52473,7 @@ var ts; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -52446,38 +52730,31 @@ var ts; if (writing === void 0) { writing = false; } var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); // For write operations, prioritize type annotations on the setter - if (writing) { - var setterParameterType_1 = getAnnotatedAccessorType(setter); - if (setterParameterType_1) { - var flags = ts.getCheckFlags(symbol); - if (flags & 1 /* Instantiated */) { - var links = getSymbolLinks(symbol); - return instantiateType(setterParameterType_1, links.mapper); - } - return setterParameterType_1; - } + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); } // Else defer to the getter type if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } // Try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + var getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + if (setterType) { + return setterType; } // If there are no specified types, try to infer it from the body of the get accessor if it exists. if (getter && getter.body) { - return getReturnTypeFromBody(getter); + var returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); } // Otherwise, fall back to 'any'. if (setter) { @@ -52494,6 +52771,13 @@ var ts; return anyType; } return undefined; + function instantiateTypeIfNeeded(type, symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); + } + return type; + } } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); @@ -52558,14 +52842,16 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); + var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontResolveAlias*/ true); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 111551 /* Value */ - ? getTypeOfSymbol(targetSymbol) - : errorType; + links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -54169,6 +54455,12 @@ var ts; } } } + function replaceIndexedAccess(instantiable, type, replacement) { + // map type.indexType to 0 + // map type.objectType to `[TReplacement]` + // thus making the indexed access `[TReplacement][0]` or `TReplacement` + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } function getIndexInfoOfIndexSymbol(indexSymbol, indexKind) { var declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); if (!declaration) @@ -54189,8 +54481,21 @@ var ts; inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ + && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ + && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) { + // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is + // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of + // type identities produced, we simplify such indexed access occurences + var newTypeParam = type.constraintType.type.objectType; + var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.mappedType = newMappedType; + inferredProp.constraintType = getIndexType(newTypeParam); + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -54404,7 +54709,7 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 2048 /* ReverseMapped */) { + else if (type.objectFlags & 1024 /* ReverseMapped */) { resolveReverseMappedTypeMembers(type); } else if (type.objectFlags & 16 /* Anonymous */) { @@ -54823,6 +55128,7 @@ var ts; return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b; var singleProp; var propSet; var indexTypes; @@ -54831,8 +55137,9 @@ var ts; var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var current = _a[_i]; + var mergedInstantiations = false; + for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) { + var current = _c[_i]; var type = getApparentType(current); if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); @@ -54848,13 +55155,25 @@ var ts; singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new ts.Map(); - propSet.set(getSymbolId(singleProp), singleProp); + var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + // If the symbols are instances of one another with identical types - consider the symbols + // equivalent and just use the first one, which thus allows us to avoid eliding private + // members when intersecting a (this-)instantiations of a class with it's raw base or another instance + if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 /* True */ : 0 /* False */; }) === -1 /* True */) { + // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used + // to do when we recorded multiple distinct symbols so that we still get, eg, `Array.length` printed + // back and not `Array.length` when we're looking at a `.length` access on a `string[] | number[]` + mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - var id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new ts.Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + var id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | @@ -54872,7 +55191,7 @@ var ts; checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0); indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304 /* ContainsSpread */)) { checkFlags |= 32 /* WritePartial */; indexTypes = ts.append(indexTypes, undefinedType); } @@ -54888,7 +55207,19 @@ var ts; return undefined; } if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + // No symbol from a union/intersection should have a `.parent` set (since unions/intersections don't act as symbol parents) + // Unless that parent is "reconstituted" from the "first value declaration" on the symbol (which is likely different than its instantiated parent!) + // They also have a `.containingType` set, which affects some services endpoints behavior, like `getRootSymbol` + var clone_1 = createSymbolWithType(singleProp, singleProp.type); + clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent; + clone_1.containingType = containingType; + clone_1.mapper = singleProp.mapper; + return clone_1; + } + else { + return singleProp; + } } var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; @@ -54897,8 +55228,8 @@ var ts; var propTypes = []; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; - for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { - var prop = props_1[_b]; + for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { + var prop = props_1[_d]; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } @@ -54975,15 +55306,15 @@ var ts; * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. */ function getReducedType(type) { - if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 67108864 /* ContainsIntersections */) { return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); } else if (type.flags & 2097152 /* Intersection */) { - if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { - type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); + if (!(type.objectFlags & 67108864 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 67108864 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 134217728 /* IsNeverIntersection */ : 0); } - return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + return type.objectFlags & 134217728 /* IsNeverIntersection */ ? neverType : type; } return type; } @@ -55013,7 +55344,7 @@ var ts; return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); } function elaborateNeverIntersection(errorInfo, type) { - if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + if (type.flags & 2097152 /* Intersection */ && ts.getObjectFlags(type) & 134217728 /* IsNeverIntersection */) { var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); @@ -55170,6 +55501,9 @@ var ts; } return false; } + function isOptionalPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && node.questionToken; + } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; @@ -55324,8 +55658,7 @@ var ts; if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) return undefined; var typeTag = ts.getJSDocTypeTag(node); - var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); @@ -55690,6 +56023,17 @@ var ts; else if (grandParent.kind === 160 /* TypeParameter */ && grandParent.parent.kind === 191 /* MappedType */) { inferences = ts.append(inferences, keyofConstraintType); } + // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends + // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template + // of the check type's mapped type + else if (grandParent.kind === 191 /* MappedType */ && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 185 /* ConditionalType */ && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 191 /* MappedType */ && + grandParent.parent.checkType.type) { + var checkMappedType_1 = grandParent.parent.checkType; + var nodeType = getTypeFromTypeNode(checkMappedType_1.type); + inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); + } } } } @@ -55763,7 +56107,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 3670016 /* PropagatingFlags */; + return result & 917504 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -55892,11 +56236,21 @@ var ts; ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } + // We refrain from associating a local type alias with an instantiation of a top-level type alias + // because the local alias may end up being referenced in an inferred return type where it is not + // accessible--which in turn may lead to a large structural expansion of the type when generating + // a .d.ts file. See #43622 for an example. var aliasSymbol = getAliasSymbolForTypeNode(node); - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol) { + var _a; + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias); + return !!(declaration && ts.getContainingFunction(declaration)); + } function getTypeReferenceName(node) { switch (node.kind) { case 174 /* TypeReference */: @@ -55992,9 +56346,17 @@ var ts; } function getConditionalFlowTypeOfType(type, node) { var constraints; + var covariant = true; while (node && !ts.isStatement(node) && node.kind !== 312 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { + // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but + // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax + if (parent.kind === 161 /* Parameter */) { + covariant = !covariant; + } + // Always substitute on type parameters, regardless of variance, since even + // in contravariant positions, they may rely on substituted constraints to be valid + if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -56586,7 +56948,7 @@ var ts; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; } else { @@ -56788,8 +57150,8 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | - (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 67108864 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } function getUnionOrIntersectionTypePredicate(signatures, kind) { @@ -56847,7 +57209,7 @@ var ts; var typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id; + "#" + origin.type.id + "|" + getTypeListId(types); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { @@ -56974,7 +57336,7 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -56983,7 +57345,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -57012,7 +57374,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -57410,7 +57772,7 @@ var ts; if (noImplicitAny) { return false; // Flag is meaningless under `noImplicitAny` mode } - if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + if (ts.getObjectFlags(type) & 8192 /* JSLiteral */) { return true; } if (type.flags & 1048576 /* Union */) { @@ -57624,6 +57986,13 @@ var ts; } return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) { + type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ | + (isGenericObjectType(type.substitute) || isGenericObjectType(type.baseType) ? 8388608 /* IsGenericObjectType */ : 0); + } + return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); + } return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type) { @@ -57634,6 +58003,13 @@ var ts; } return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) { + type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ | + (isGenericIndexType(type.substitute) || isGenericIndexType(type.baseType) ? 33554432 /* IsGenericIndexType */ : 0); + } + return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); + } return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type); } function isThisTypeParameter(type) { @@ -57891,7 +58267,7 @@ var ts; // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { var isUnwrapped = isTypicalNondistributiveConditional(root); - var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { @@ -57904,7 +58280,7 @@ var ts; // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); } // It's possible for 'infer T' type paramteters to be given uninstantiated constraints when the // those type parameters are used in type references (see getInferredTypeParameterConstraint). For @@ -58161,7 +58537,7 @@ var ts; } } var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return spread; } } @@ -58267,7 +58643,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */ | 4194304 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ @@ -58687,8 +59063,9 @@ var ts; outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || ts.emptyArray; - typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? - ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) : + var allDeclarations_1 = type.objectFlags & 4 /* Reference */ ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) : typeParameters; links.outerTypeParameters = typeParameters; } @@ -58733,7 +59110,7 @@ var ts; return true; } } - return !!ts.forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node) { @@ -58745,6 +59122,9 @@ var ts; getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality case 177 /* TypeQuery */: return true; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + return (!node.type && !!node.body) || !!ts.forEachChild(node, containsReference); } return !!ts.forEachChild(node, containsReference); } @@ -58924,6 +59304,9 @@ var ts; var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; } + if (objectFlags & 1024 /* ReverseMapped */) { + return instantiateReverseMappedType(type, mapper); + } return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; @@ -58973,6 +59356,21 @@ var ts; } return type; } + function instantiateReverseMappedType(type, mapper) { + var innerMappedType = instantiateType(type.mappedType, mapper); + if (!(ts.getObjectFlags(innerMappedType) & 32 /* Mapped */)) { + return type; + } + var innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304 /* Index */)) { + return type; + } + var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); + if (instantiated) { + return instantiated; + } + return type; // Nested invocation of `inferTypeForHomomorphicMappedType` or the `source` instantiated into something unmappable + } function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -59888,7 +60286,7 @@ var ts; return false; } function isIgnoredJsxProperty(source, sourceProp) { - return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); + return ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { while (true) { @@ -59898,6 +60296,7 @@ var ts; type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; @@ -60215,7 +60614,7 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1 /* True */; } - reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */)); return 0 /* False */; } // Normalize the source and target types: Turn fresh literal types into regular literal types, @@ -60258,8 +60657,8 @@ var ts; if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); + var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -60344,7 +60743,7 @@ var ts; // We suppress recursive intersection property checks because they can generate lots of work when relating // recursive intersections that are structurally similar but not exactly identical. See #37854. if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); inPropertyCheck = false; @@ -60353,8 +60752,10 @@ var ts; return result; function reportErrorResults(source, target, result, isComparingJsxAttributes) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; var maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -60401,7 +60802,7 @@ var ts; if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { var sourceUnionOrIntersection = source; var targetUnionOrIntersection = target; - if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144 /* PrimitiveUnion */) { + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536 /* PrimitiveUnion */) { // There's a fast path for comparing primitive unions return; } @@ -60426,11 +60827,11 @@ var ts; } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & 3145728 /* UnionOrIntersection */) { - var result_6 = eachTypeRelatedToSomeType(source, target); - if (result_6) { - result_6 &= eachTypeRelatedToSomeType(target, source); + var result_7 = eachTypeRelatedToSomeType(source, target); + if (result_7) { + result_7 &= eachTypeRelatedToSomeType(target, source); } - return result_6; + return result_7; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -60445,10 +60846,10 @@ var ts; } function hasExcessProperties(source, target, reportErrors) { var _a; - if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; @@ -60862,21 +61263,21 @@ var ts; if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_7 = 0 /* False */; + var result_8 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_8; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_8; } } } @@ -60956,6 +61357,20 @@ var ts; } } else if (target.flags & 8388608 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { + // Relate components directly before falling back to constraint relationships + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } // A type S is related to a type T[K] if S is related to C, where C is the base // constraint of T[K] for writing. if (relation === assignableRelation || relation === comparableRelation) { @@ -60966,11 +61381,24 @@ var ts; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0); var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + // create a new chain for the constraint error + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { // A source type T is related to a target type { [P in X]: T[P] } @@ -61048,23 +61476,14 @@ var ts; // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - var result_8 = inferTypesFromTemplateLiteralType(source, target); - if (result_8 && ts.every(result_8, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + var result_9 = inferTypesFromTemplateLiteralType(source, target); + if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { return -1 /* True */; } } if (source.flags & 8650752 /* TypeVariable */) { - if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { - // A type S[K] is related to a type T[J] if S is related to T and K is related to J. - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - result &= isRelatedTo(source.indexType, target.indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - else { + // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch + if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) { var constraint = getConstraintOfType(source); if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. @@ -61079,7 +61498,7 @@ var ts; 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, reportErrors, /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -61091,6 +61510,16 @@ var ts; return result; } } + else if (source.flags & 134217728 /* TemplateLiteral */) { + if (!(target.flags & 134217728 /* TemplateLiteral */)) { + var baseConstraint = getBaseConstraintOfType(source); + var constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; + } + } + } else if (source.flags & 268435456 /* StringMapping */) { if (target.flags & 268435456 /* StringMapping */ && source.symbol === target.symbol) { if (result = isRelatedTo(source.type, target.type, reportErrors)) { @@ -61117,7 +61546,7 @@ var ts; if (sourceParams) { // If the source has infer type parameters, we instantiate them in the context of the target var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } @@ -61175,7 +61604,7 @@ var ts; return 0 /* False */; } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && - !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + !(ts.getObjectFlags(source) & 4096 /* MarkerType */ || ts.getObjectFlags(target) & 4096 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. @@ -61203,7 +61632,7 @@ var ts; } // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})` // and not `{} <- fresh({}) <- {[idx: string]: any}` - else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) { + else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 /* FreshLiteral */ && !isEmptyObjectType(source)) { return 0 /* False */; } // Even if relationship doesn't hold for unions, intersections, or generic type references, @@ -61241,14 +61670,19 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_9) { - return result_9; + var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_10) { + return result_10; } } } } return 0 /* False */; + function countMessageChainBreadth(info) { + if (!info) + return 0; + return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0); + } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -61310,13 +61744,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_10; + var result_11; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } } @@ -61456,7 +61890,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_11 = unionParent ? 0 /* False */ : -1 /* True */; + var result_12 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -61466,7 +61900,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_11 &= related; + result_12 &= related; } else { if (related) { @@ -61474,17 +61908,17 @@ var ts; } } } - if (unionParent && !result_11 && targetIsOptional) { - result_11 = isRelatedTo(source, undefinedType); + if (unionParent && !result_12 && targetIsOptional) { + result_12 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_11 && reportErrors) { + if (unionParent && !result_12 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_11; + return result_12; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); @@ -62086,7 +62520,7 @@ var ts; // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); - result.objectFlags |= 8192 /* MarkerType */; + result.objectFlags |= 4096 /* MarkerType */; return result; } function getAliasVariances(symbol) { @@ -62260,8 +62694,8 @@ var ts; } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. - function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons @@ -62279,23 +62713,26 @@ var ts; function isDeeplyNestedType(type, stack, depth) { if (depth >= 5) { var identity_1 = getRecursionIdentity(type); - if (identity_1) { - var count = 0; - for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= 5) { - return true; - } + var count = 0; + for (var i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity_1) { + count++; + if (count >= 5) { + return true; } } } } return false; } - // Types with constituents that could circularly reference the type have a recursion identity. The recursion - // identity is some object that is common to instantiations of the type with the same origin. + // The recursion identity of a type is an object identity that is shared among multiple instantiations of the type. + // We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with + // the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all + // instantiations of that type have the same recursion identity. The default recursion identity is the object + // identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly + // reference the type have a recursion identity that differs from the object identity. function getRecursionIdentity(type) { + // Object and array literals are known not to contain recursive references and don't need a recursion identity. if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) { // Deferred type references are tracked through their associated AST node. This gives us finer @@ -62313,6 +62750,9 @@ var ts; return type.target; } } + if (type.flags & 262144 /* TypeParameter */) { + return type.symbol; + } if (type.flags & 8388608 /* IndexedAccess */) { // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A do { @@ -62324,7 +62764,7 @@ var ts; // The root object represents the origin of the conditional type return type.root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; @@ -62462,6 +62902,9 @@ var ts; // 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; }); @@ -62494,12 +62937,30 @@ var ts; function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return isArrayType(type) || hasArrayOrReadonlyArrayBaseType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } - function hasArrayOrReadonlyArrayBaseType(type) { - return !!(ts.getObjectFlags(type) & 4 /* Reference */) - && !!(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */) - && ts.some(getBaseTypes(type.target), isArrayType); + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */)) { + return undefined; + } + if (ts.getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) { + return ts.getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : undefined; + } + type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */; + var target = type.target; + var bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; // If the interface has any members, they may subtype members in the base, so we should do a full structural comparison + } + var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type))); + } + type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */; + return type.cachedEquivalentBaseType = instantiatedBase; } function isEmptyArrayLiteralType(type) { var elementType = getElementTypeOfArrayType(type); @@ -62744,7 +63205,7 @@ var ts; function isObjectTypeWithInferableIndex(type) { return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */); @@ -62777,7 +63238,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -62788,7 +63249,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */; + regularNew.objectFlags |= resolved.objectFlags & ~16384 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -62818,7 +63279,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; - if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304 /* ContainsSpread */)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; names.set(prop.escapedName, prop); @@ -62867,14 +63328,14 @@ var ts; var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (8192 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -62919,7 +63380,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -62945,7 +63406,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -63025,7 +63486,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -63141,16 +63602,16 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) { - return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); + if (objectFlags & 1048576 /* CouldContainTypeVariablesComputed */) { + return !!(objectFlags & 2097152 /* CouldContainTypeVariables */); } var result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 8388608 /* ObjectRestType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { - type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); + type.objectFlags |= 1048576 /* CouldContainTypeVariablesComputed */ | (result ? 2097152 /* CouldContainTypeVariables */ : 0); } return result; } @@ -63210,7 +63671,7 @@ var ts; // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive // arrow function, but is considered partially inferable because property 'a' has an inferable type. function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 524288 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) || isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType); } @@ -63234,14 +63695,18 @@ var ts; } // For all other object types we infer a new object type where the reverse mapping has been // applied to the type of each property. - var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + var reversed = createObjectType(1024 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType, target, constraint) { var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); @@ -63439,7 +63904,7 @@ var ts; if (contravariant === void 0) { contravariant = false; } var bivariant = false; var propagationType; - var inferencePriority = 1024 /* MaxValue */; + var inferencePriority = 2048 /* MaxValue */; var allowComplexConstraintInference = true; var visited; var sourceStack; @@ -63526,8 +63991,8 @@ var ts; // 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 (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || - (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || + (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -63554,7 +64019,7 @@ var ts; clearCachedInferences(inferences); } } - if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -63594,7 +64059,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - inferWithPriority(empty, target.type, 128 /* LiteralKeyof */); + inferWithPriority(empty, target.type, 256 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -63606,6 +64071,13 @@ var ts; inferFromTypes(source.type, target.type); } } + else if (source.flags & 33554432 /* Substitution */) { + inferFromTypes(source.baseType, target); + var oldPriority = priority; + priority |= 4 /* SubstituteSource */; + inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority + priority = oldPriority; + } else if (target.flags & 16777216 /* Conditional */) { invokeOnce(source, target, inferToConditionalType); } @@ -63625,7 +64097,7 @@ var ts; } else { source = getReducedType(source); - if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { + if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` @@ -63663,26 +64135,22 @@ var ts; } (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */); var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; // We stop inferring and report a circularity if we encounter duplicate recursion identities on both // the source side and the target side. var saveExpandingFlags = expandingFlags; - var sourceIdentity = getRecursionIdentity(source) || source; - var targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && ts.contains(sourceStack, sourceIdentity)) + var sourceIdentity = getRecursionIdentity(source); + var targetIdentity = getRecursionIdentity(target); + if (ts.contains(sourceStack, sourceIdentity)) expandingFlags |= 1 /* Source */; - if (targetIdentity && ts.contains(targetStack, targetIdentity)) + if (ts.contains(targetStack, targetIdentity)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { - if (sourceIdentity) - (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) - (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) - targetStack.pop(); - if (sourceIdentity) - sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = -1 /* Circularity */; @@ -63722,7 +64190,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -63774,7 +64242,7 @@ var ts; else { for (var i = 0; i < sources.length; i++) { var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; inferFromTypes(sources[i], t); if (inferencePriority === priority) matched_1[i] = true; @@ -63853,7 +64321,7 @@ var ts; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? 8 /* PartialHomomorphicMappedType */ : 4 /* HomomorphicMappedType */); + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 /* NonInferrableType */ ? 16 /* PartialHomomorphicMappedType */ : 8 /* HomomorphicMappedType */); } } return true; @@ -63861,7 +64329,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */); + inferWithPriority(getIndexType(source), constraintType, 32 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -63890,7 +64358,7 @@ var ts; } else { var savePriority = priority; - priority |= contravariant ? 32 /* ContravariantConditional */ : 0; + priority |= contravariant ? 64 /* ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, target.flags); priority = savePriority; @@ -64013,7 +64481,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -64064,7 +64532,7 @@ var ts; return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); } function isObjectOrArrayLiteralType(type) { - return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */)); + return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 32768 /* ArrayLiteral */)); } function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { @@ -64077,7 +64545,7 @@ var ts; return candidates; } function getContravariantInference(inference) { - return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } function getCovariantInference(inference, signature) { // Extract all object and array literal types and replace them with a single widened and normalized type. @@ -64094,7 +64562,7 @@ var ts; candidates; // If all inferences were made from a position that implies a combined result, infer a union type. // Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ? + var unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -64391,14 +64859,14 @@ var ts; function getKeyPropertyName(unionType) { var types = unionType.types; // We only construct maps for large unions with non-primitive constituents. - if (types.length < 10 || ts.getObjectFlags(unionType) & 262144 /* PrimitiveUnion */) { + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { return undefined; } if (unionType.keyPropertyName === undefined) { // The candidate key property name is the name of the first property with a unit type in one of the // constituent types. var keyPropertyName = ts.forEach(types, function (t) { - return t.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? + return t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) : undefined; }); @@ -64493,7 +64961,8 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, ignoreObjects) { + if (ignoreObjects === void 0) { ignoreObjects = false; } var flags = type.flags; if (flags & 4 /* String */) { return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; @@ -64530,7 +64999,7 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 524288 /* Object */) { + if (flags & 524288 /* Object */ && !ignoreObjects) { return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? @@ -64553,14 +65022,17 @@ var ts; return 0 /* None */; } if (flags & 465829888 /* Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */; } if (flags & 1048576 /* Union */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t); }, 0 /* None */); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* None */); } if (flags & 2097152 /* Intersection */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t); }, 16777215 /* All */); + // 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 /* Primitive */)); + return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */); } return 16777215 /* All */; } @@ -64769,6 +65241,9 @@ var ts; function everyType(type, f) { return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } + function everyContainedType(type, f) { + return type.flags & 3145728 /* UnionOrIntersection */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 1048576 /* Union */) { var types = type.types; @@ -66069,7 +66544,16 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); + return filterType(type, function (t) { + if (!isRelated(t, candidate)) { + return true; + } + var constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } // 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. @@ -66164,17 +66648,20 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 78 /* Identifier */) { + if (location.kind === 78 /* Identifier */ || location.kind === 79 /* PrivateIdentifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true); + } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the @@ -66299,7 +66786,6 @@ var ts; } } function checkIdentifier(node, checkMode) { - var _a; var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -66401,7 +66887,7 @@ var ts; } } else if (isAlias) { - declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -66614,7 +67100,7 @@ var ts; break; case 164 /* PropertyDeclaration */: case 163 /* PropertySignature */: - if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } @@ -67257,16 +67743,16 @@ var ts; // In an assignment expression, the right operand is contextually typed by the type of the left operand. // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return getTypeOfExpression(binaryExpression.left); + case 4 /* ThisProperty */: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case 5 /* Property */: - case 1 /* ExportsProperty */: - case 6 /* Prototype */: - case 3 /* PrototypeProperty */: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. @@ -67287,11 +67773,11 @@ var ts; var id = lhs.expression; var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true); if (parentSymbol) { - var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); - if (annotated) { + var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated_1) { var nameStr = ts.getElementOrPropertyAccessName(lhs); if (nameStr !== undefined) { - return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr); + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr); } } return undefined; @@ -67299,9 +67785,15 @@ var ts; } return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; + // falls through case 2 /* ModuleExports */: - case 4 /* ThisProperty */: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); + var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case 7 /* ObjectDefinePropertyValue */: case 8 /* ObjectDefinePropertyExports */: case 9 /* ObjectDefinePrototypeProperty */: @@ -67322,7 +67814,7 @@ var ts; var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true); return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) { + function getContextualTypeForThisPropertyAssignment(binaryExpression) { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { @@ -67334,8 +67826,6 @@ var ts; } } } - if (kind === 2 /* ModuleExports */) - return undefined; var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression); if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return undefined; @@ -67390,6 +67880,10 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { if (hasBindableName(element)) { @@ -67487,10 +67981,10 @@ var ts; return false; } function discriminateContextualTypeByObjectMembers(node, contextualType) { - return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -67599,7 +68093,7 @@ var ts; case 290 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent, contextFlags); case 291 /* SpreadAssignment */: - return getApparentTypeOfContextualType(parent.parent, contextFlags); + return getContextualType(parent.parent, contextFlags); case 200 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); @@ -67995,7 +68489,7 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 32768 /* ArrayLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; } return literalType; } @@ -68152,7 +68646,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -68280,9 +68774,9 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { - result.objectFlags |= 16384 /* JSLiteral */; + result.objectFlags |= 8192 /* JSLiteral */; } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -68372,14 +68866,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var objectFlags = 4096 /* JsxAttributes */; + var objectFlags = 2048 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -68463,7 +68957,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -68965,7 +69459,7 @@ var ts; // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { @@ -69140,6 +69634,23 @@ var ts; if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); } + if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (compilerOptions.target === 99 /* ESNext */ && !useDefineForClassFields)) { + var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); + var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { + if (n === lexicalClass_1) + return "quit"; + if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); + } + } if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -69229,7 +69740,10 @@ var ts; // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + prop && + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) + && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { @@ -69272,6 +69786,7 @@ var ts; var diagnosticMessage; var declarationName = ts.idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { @@ -69377,7 +69892,10 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + var diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : ts.Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -69388,6 +69906,11 @@ var ts; } diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) && + isEmptyObjectType(containingType); + } function typeHasStaticProperty(propName, containingType) { var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); return prop !== undefined && !!prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); @@ -69854,7 +70377,7 @@ var ts; }); if (!inferenceContext) { applyToReturnTypes(contextualSignature, signature, function (source, target) { - inferTypes(context.inferences, source, target, 64 /* ReturnType */); + inferTypes(context.inferences, source, target, 128 /* ReturnType */); }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); @@ -69904,7 +70427,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* 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 @@ -70349,77 +70872,66 @@ var ts; return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - var belowArgCount = Number.NEGATIVE_INFINITY; - var aboveArgCount = Number.POSITIVE_INFINITY; - var argCount = args.length; + var _a; + var spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } + var min = Number.POSITIVE_INFINITY; // smallest parameter count + var max = Number.NEGATIVE_INFINITY; // largest parameter count + var maxBelow = Number.NEGATIVE_INFINITY; // largest parameter count that is smaller than the number of arguments + var minAbove = Number.POSITIVE_INFINITY; // smallest parameter count that is larger than the number of arguments var closestSignature; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var sig = signatures_8[_i]; - var minCount = getMinArgumentCount(sig); - var maxCount = getParameterCount(sig); - if (minCount < argCount && minCount > belowArgCount) - belowArgCount = minCount; - if (argCount < maxCount && maxCount < aboveArgCount) - aboveArgCount = maxCount; - if (minCount < min) { - min = minCount; + var minParameter = getMinArgumentCount(sig); + var maxParameter = getParameterCount(sig); + // smallest/largest parameter counts + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + max = Math.max(max, maxParameter); + // shortest parameter count *longer than the call*/longest parameter count *shorter than the call* + if (minParameter < args.length && minParameter > maxBelow) + maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) + minAbove = maxParameter; } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); - var paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var spanArray; - var related; - var error = hasRestParameter || hasSpreadArgument ? - hasRestParameter && hasSpreadArgument ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - ts.Diagnostics.Expected_0_arguments_but_got_1; - if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { - var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; - if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : - ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); - } - } - if (!hasSpreadArgument && argCount < min) { - var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } - if (hasRestParameter || hasSpreadArgument) { - spanArray = ts.factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); + var parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : ts.Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + // between min and max, but with no matching overload + return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + // too short: put the error span on the call expression, not any of the args + var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined); + return ts.addRelatedInfo(diagnostic, parameterError); } + return diagnostic; } else { - spanArray = ts.factory.createNodeArray(args.slice(max)); - } - var pos = ts.first(spanArray).pos; - var end = ts.last(spanArray).end; - if (end === pos) { - end++; + // too long; error goes on the excess parameters + var errorSpan = ts.factory.createNodeArray(args.slice(max)); + var pos = ts.first(errorSpan).pos; + var end = ts.last(errorSpan).end; + if (end === pos) { + end++; + } + ts.setTextRangePosEnd(errorSpan, pos, end); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - ts.setTextRangePosEnd(spanArray, pos, end); - var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -71512,7 +72024,7 @@ var ts; var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false); if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) { var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + jsAssignmentType.objectFlags |= 8192 /* JSLiteral */; return getIntersectionType([returnType, jsAssignmentType]); } } @@ -71944,7 +72456,14 @@ var ts; } } function assignContextualParameterTypes(signature, context) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; // This signature has already has a contextual inference performed and cached on it! + } + } if (context.thisParameter) { var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { @@ -72337,17 +72856,17 @@ var ts; return; } var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */; + var errorNode = ts.getEffectiveReturnTypeNode(func) || func; if (type && type.flags & 131072 /* Never */) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { // minimal check: function has syntactic return type annotation and no explicit return statements in the body // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -72362,7 +72881,7 @@ var ts; return; } } - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { @@ -72382,7 +72901,7 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; + returnOnlyType.objectFlags |= 524288 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } } @@ -74183,7 +74702,7 @@ var ts; checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { if (!(func.kind === 167 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } @@ -74640,9 +75159,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); })); + ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -74694,15 +75213,18 @@ var ts; var symbol = getSymbolOfNode(node); var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); - if (getter && setter) { + if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) { + getNodeLinks(getter).flags |= 1 /* TypeChecked */; var getterFlags = ts.getEffectiveModifierFlags(getter); var setterFlags = ts.getEffectiveModifierFlags(setter); if ((getterFlags & 128 /* Abstract */) !== (setterFlags & 128 /* Abstract */)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } if (((getterFlags & 16 /* Protected */) && !(setterFlags & (16 /* Protected */ | 8 /* Private */))) || ((getterFlags & 8 /* Private */) && !(setterFlags & 8 /* Private */))) { - error(node.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } var getterType = getAnnotatedAccessorType(getter); var setterType = getAnnotatedAccessorType(setter); @@ -75262,20 +75784,23 @@ var ts; case 298 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: + var node_2 = d; + var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values - if (!ts.isEntityNameExpression(d.expression)) { + if (!ts.isEntityNameExpression(expression)) { return 1 /* ExportValue */; } - d = d.expression; + d = expression; // The below options all declare an Alias, which is allowed to merge with other values within the importing module. // falls through case 261 /* ImportEqualsDeclaration */: case 264 /* NamespaceImport */: case 263 /* ImportClause */: - var result_12 = 0 /* None */; + var result_13 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); - return result_12; + ts.forEach(target.declarations, function (d) { result_13 |= getDeclarationSpaces(d); }); + return result_13; case 250 /* VariableDeclaration */: case 199 /* BindingElement */: case 252 /* FunctionDeclaration */: @@ -76596,11 +77121,6 @@ var ts; return; if (getFalsyFlags(type)) return; - if (getAwaitedTypeOfPromise(type)) { - errorAndMaybeSuggestAwait(condExpr, - /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined, getTypeNameForErrorDisplay(type)); - return; - } var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr; var testedNode = ts.isIdentifier(location) ? location : ts.isPropertyAccessExpression(location) ? location.name @@ -76612,25 +77132,32 @@ var ts; return; } // While it technically should be invalid for any known-truthy value - // to be tested, we de-scope to functions unrefenced in the block as a - // heuristic to identify the most common bugs. There are too many - // false positives for values sourced from type definitions without - // strictNullChecks otherwise. + // to be tested, we de-scope to functions and Promises unreferenced in + // the block as a heuristic to identify the most common bugs. There + // are too many false positives for values sourced from type + // definitions without strictNullChecks otherwise. var callSignatures = getSignaturesOfType(type, 0 /* Call */); - if (callSignatures.length === 0) { + var isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } var testedSymbol = getSymbolAtLocation(testedNode); if (!testedSymbol) { return; } - var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + var isUsed = ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait(location, + /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); + } + else { + error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) { + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { return !!ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); @@ -76667,7 +77194,7 @@ var ts; return ts.forEachChild(childNode, check); }); } - function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) { + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { var isUsed = ts.forEachChild(node.right, function visit(child) { if (ts.isIdentifier(child)) { @@ -77990,7 +78517,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - checkMembersForMissingOverrideModifier(node, type, typeWithThis); + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -78025,12 +78552,16 @@ var ts; checkPropertyInitialization(node); } } - function checkMembersForMissingOverrideModifier(node, type, typeWithThis) { + function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); var baseTypeNode = ts.getEffectiveBaseTypeNode(node); var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); var _loop_24 = function (member) { + if (ts.hasAmbientModifier(member)) { + return "continue"; + } if (ts.isConstructorDeclaration(member)) { ts.forEach(member.parameters, function (param) { if (ts.isParameterPropertyDeclaration(param, member)) { @@ -78046,14 +78577,17 @@ var ts; } function checkClassMember(member, memberIsParameterProperty) { var hasOverride = ts.hasOverrideModifier(member); + var hasStatic = ts.hasStaticModifier(member); if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); if (!declaredProp) { return; } + var thisType = hasStatic ? staticType : typeWithThis; + var baseType = hasStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); var baseClassName = typeToString(baseWithThis); - var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); - var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && !baseProp && hasOverride) { error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } @@ -78064,7 +78598,7 @@ var ts; } if (!baseHasAbstract) { var diag = memberIsParameterProperty ? - ts.Diagnostics.This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; error(member, diag, baseClassName); } @@ -78218,7 +78752,7 @@ var ts; ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { + else if (useDefineForClassFields) { var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 164 /* PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* Transient */) @@ -79094,7 +79628,10 @@ var ts; } } function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + var illegalContextMessage = node.isExportEquals + ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } @@ -79183,10 +79720,12 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, _b = declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (var _i = 0, _b = declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } } @@ -79195,6 +79734,11 @@ var ts; links.exportsChecked = true; } } + function isDuplicatedCommonJSExport(declarations) { + return declarations + && declarations.length > 1 + && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); }); + } function checkSourceElement(node) { if (node) { var saveCurrentNode = currentNode; @@ -79425,7 +79969,8 @@ var ts; if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_1) { + var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent); + if (host_1 || isCallbackTag) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -79433,7 +79978,9 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var lastParamDeclaration = isCallbackTag + ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) + : ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -79649,11 +80196,11 @@ var ts; } switch (location.kind) { case 298 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) + if (!ts.isExternalModule(location)) break; // falls through case 257 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; case 256 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); @@ -79716,6 +80263,16 @@ var ts; }); } } + function copyLocallyVisibleExportSymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + // Similar condition as in `resolveNameHelper` + if (!ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 270 /* NamespaceExport */)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name) { return name.kind === 78 /* Identifier */ && @@ -79755,14 +80312,14 @@ var ts; } return node.parent.kind === 224 /* ExpressionWithTypeArguments */; } - function isJSDocEntryNameReference(node) { + function getJSDocEntryNameReference(node) { while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 303 /* JSDocNameReference */; + return ts.isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node, callback) { var result; @@ -79924,18 +80481,34 @@ var ts; var meaning = name.parent.kind === 174 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (isJSDocEntryNameReference(name)) { - var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); - } - else if (ts.isJSDocLink(name.parent)) { + var jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || ts.isJSDocLink(name.parent)) { var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ true); + var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ false, ts.getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (ts.isQualifiedName(name) && ts.isIdentifier(name.left)) { + // resolve C.m as a static member first + var links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, 0 /* Normal */); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + // then resolve it as an instance member + var s = resolveEntityName(name.left, meaning, /*ignoreErrors*/ false); + if (s) { + var t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } } if (name.parent.kind === 173 /* TypePredicate */) { return resolveEntityName(name, 1 /* FunctionScopedVariable */); } - // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node, ignoreErrors) { @@ -80135,10 +80708,10 @@ var ts; // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { if (expr.parent.kind === 289 /* PropertyAssignment */) { - var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); - var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType; - var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent); - return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex); + var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); + var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; + var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex); } // Array literal assignment - array destructuring pattern var node = ts.cast(expr.parent, ts.isArrayLiteralExpression); @@ -80492,13 +81065,13 @@ var ts; !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && !!parameter.initializer && - !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + !ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameter(parameter) { return !!strictNullChecks && @@ -81206,17 +81779,18 @@ var ts; } break; case 156 /* OverrideKeyword */: + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override"); } else if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); } - else if (flags & 32 /* Static */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "override"); + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); } - if (node.kind === 161 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "override"); + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); } flags |= 16384 /* Override */; lastOverride = modifier; @@ -81228,7 +81802,7 @@ var ts; if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + else if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); } else if (flags & 32 /* Static */) { @@ -81263,9 +81837,6 @@ var ts; else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "override"); - } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } @@ -81278,6 +81849,9 @@ var ts; else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); + } flags |= 32 /* Static */; lastStatic = modifier; break; @@ -81286,7 +81860,7 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } else if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */ && node.kind !== 172 /* IndexSignature */ && node.kind !== 161 /* Parameter */) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; @@ -81327,7 +81901,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + else if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); } else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { @@ -81369,6 +81943,9 @@ var ts; if (flags & 256 /* Async */ && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -81400,7 +81977,7 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } - if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + if (flags & 16384 /* Override */) { return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 } else if (flags & 256 /* Async */) { @@ -81414,10 +81991,10 @@ var ts; else if ((node.kind === 262 /* ImportDeclaration */ || node.kind === 261 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 161 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 161 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -82701,20 +83278,6 @@ var ts; return ts.isDeclarationName(name); } } - function isSomeImportDeclaration(decl) { - switch (decl.kind) { - case 263 /* ImportClause */: // For default import - case 261 /* ImportEqualsDeclaration */: - case 264 /* NamespaceImport */: - case 266 /* ImportSpecifier */: - return true; - case 78 /* Identifier */: - // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 266 /* ImportSpecifier */; - default: - return false; - } - } var JsxNames; (function (JsxNames) { JsxNames.JSX = "JSX"; @@ -87584,10 +88147,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_1 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_1, node); - ts.setCommentRange(clone_1, node); - return clone_1; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -87672,6 +88235,7 @@ var ts; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var shouldTransformPrivateElements = languageVersion < 99 /* ESNext */; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; @@ -87693,7 +88257,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === 99 /* ESNext */) { + || useDefineForClassFields && options.target === 99 /* ESNext */) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -87852,7 +88416,7 @@ var ts; // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } @@ -88163,7 +88727,7 @@ var ts; if (ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. return languageVersion < 99 /* ESNext */; @@ -88186,7 +88750,6 @@ var ts; /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); @@ -88298,7 +88861,7 @@ var ts; function transformProperty(property, receiver) { var _a; // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) - var emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + var emitAssignment = !useDefineForClassFields; var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; @@ -88403,10 +88966,10 @@ var ts; 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; + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; } } } @@ -90568,9 +91131,9 @@ var ts; function convertJsxChildrenToChildrenPropObject(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) + var result_14 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_14 && factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("children", result_14) ]); } var result = ts.mapDefined(children, transformJsxChildToExpression); @@ -92302,7 +92865,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName); var e; - if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) { var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; @@ -93125,13 +93688,13 @@ var ts; loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); - loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); + loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { - var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; @@ -96077,10 +96640,10 @@ var ts; var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { // TODO(rbuckton): Does this need to be parented? - var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); - ts.setSourceMapRange(clone_5, node); - ts.setCommentRange(clone_5, node); - return clone_5; + var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -97074,8 +97637,6 @@ var ts; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(204 /* CallExpression */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(206 /* TaggedTemplateExpression */); // Substitutes expression identifiers with imported/exported symbols. context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. @@ -97086,7 +97647,6 @@ var ts; var currentModuleInfo; // The ExternalModuleInfo for the current file. var noSubstitution; // Set of nodes for which substitution rules should be ignored. var needUMDDynamicImportHelper; - var bindingReferenceCache; return ts.chainBundle(context, transformSourceFile); /** * Transforms the module aspects of a SourceFile. @@ -98333,10 +98893,6 @@ var ts; return substituteExpressionIdentifier(node); case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 204 /* CallExpression */: - return substituteCallExpression(node); - case 206 /* TaggedTemplateExpression */: - return substituteTaggedTemplateExpression(node); case 216 /* PostfixUnaryExpression */: case 215 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); @@ -98344,99 +98900,41 @@ var ts; return node; } /** - * For an Identifier, gets the import or export binding that it references. - * @returns One of the following: - * - An `Identifier` if node references an external helpers module (i.e., `tslib`). - * - A `SourceFile` if the node references an export in the file. - * - An `ImportClause` or `ImportSpecifier` if the node references an import binding. - * - Otherwise, `undefined`. + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. */ - function getImportOrExportBindingReferenceWorker(node) { + function substituteExpressionIdentifier(node) { + var _a, _b; if (ts.getEmitFlags(node) & 4096 /* HelperName */) { var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); if (externalHelpersModuleName) { - return externalHelpersModuleName; + return factory.createPropertyAccessExpression(externalHelpersModuleName, node); } + return node; } else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if ((exportContainer === null || exportContainer === void 0 ? void 0 : exportContainer.kind) === 298 /* SourceFile */) { - return exportContainer; + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { + return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), + /*location*/ node); } var importDeclaration = resolver.getReferencedImportDeclaration(node); - if (importDeclaration && (ts.isImportClause(importDeclaration) || ts.isImportSpecifier(importDeclaration))) { - return importDeclaration; - } - } - return undefined; - } - /** - * For an Identifier, gets the import or export binding that it references. - * @param removeEntry When `false`, the result is cached to avoid recomputing the result in a later substitution. - * When `true`, any cached result for the node is removed. - * @returns One of the following: - * - An `Identifier` if node references an external helpers module (i.e., `tslib`). - * - A `SourceFile` if the node references an export in the file. - * - An `ImportClause` or `ImportSpecifier` if the node references an import binding. - * - Otherwise, `undefined`. - */ - function getImportOrExportBindingReference(node, removeEntry) { - var result = bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.get(node); - if (!result && !(bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.has(node))) { - result = getImportOrExportBindingReferenceWorker(node); - if (!removeEntry) { - bindingReferenceCache || (bindingReferenceCache = new ts.Map()); - bindingReferenceCache.set(node, result); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || importDeclaration), factory.cloneNode(name)), + /*location*/ node); + } } } - else if (removeEntry) { - bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.delete(node); - } - return result; - } - function substituteCallExpression(node) { - if (ts.isIdentifier(node.expression) && getImportOrExportBindingReference(node.expression, /*removeEntry*/ false)) { - return ts.isCallChain(node) ? - factory.updateCallChain(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.expression), node.expression), node.questionDotToken, - /*typeArguments*/ undefined, node.arguments) : - factory.updateCallExpression(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.expression), node.expression), - /*typeArguments*/ undefined, node.arguments); - } - return node; - } - function substituteTaggedTemplateExpression(node) { - if (ts.isIdentifier(node.tag) && getImportOrExportBindingReference(node.tag, /*removeEntry*/ false)) { - return factory.updateTaggedTemplateExpression(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.tag), node.tag), - /*typeArguments*/ undefined, node.template); - } return node; } - /** - * Substitution for an Identifier expression that may contain an imported or exported - * symbol. - * - * @param node The node to substitute. - */ - function substituteExpressionIdentifier(node) { - var _a, _b; - var result = getImportOrExportBindingReference(node, /*removeEntry*/ true); - switch (result === null || result === void 0 ? void 0 : result.kind) { - case 78 /* Identifier */: - return factory.createPropertyAccessExpression(result, node); - case 298 /* SourceFile */: - return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), - /*location*/ node); - case 263 /* ImportClause */: - return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(result.parent), factory.createIdentifier("default")), - /*location*/ node); - case 266 /* ImportSpecifier */: - var name = result.propertyName || result.name; - return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = result.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || result), factory.cloneNode(name)), - /*location*/ node); - default: - return node; - } - } /** * Substitution for a BinaryExpression that may contain an imported or exported symbol. * @@ -99698,7 +100196,7 @@ var ts; return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } /** - * Determines whether the target of a destructuring assigment refers to an exported symbol. + * Determines whether the target of a destructuring assignment refers to an exported symbol. * * @param node The destructuring target. */ @@ -100882,7 +101380,7 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, + var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, /*preferences*/ undefined); if (!ts.pathIsRelative(specifier)) { // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration @@ -101628,7 +102126,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param)) + if (!ts.hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 78 /* Identifier */) { @@ -102413,32 +102911,32 @@ var ts; } ts.transformNodes = transformNodes; ts.nullTransformationContext = { - get factory() { return ts.factory; }, - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: ts.returnUndefined, + factory: ts.factory, getCompilerOptions: function () { return ({}); }, - getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + getEmitHost: ts.notImplemented, getEmitHelperFactory: ts.notImplemented, + startLexicalEnvironment: ts.noop, + resumeLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + endLexicalEnvironment: ts.returnUndefined, setLexicalEnvironmentFlags: ts.noop, getLexicalEnvironmentFlags: function () { return 0; }, - hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + hoistFunctionDeclaration: ts.noop, addInitializationStatement: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop, - addDiagnostic: ts.noop, startBlockScope: ts.noop, endBlockScope: ts.returnUndefined, - addBlockScopedVariable: ts.noop + addBlockScopedVariable: ts.noop, + requestEmitHelper: ts.noop, + readEmitHelpers: ts.notImplemented, + enableSubstitution: ts.noop, + enableEmitNotification: ts.noop, + isSubstitutionEnabled: ts.notImplemented, + isEmitNotificationEnabled: ts.notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, + addDiagnostic: ts.noop, }; })(ts || (ts = {})); var ts; @@ -103187,10 +103685,18 @@ var ts; return outputFiles; } ts.emitUsingBuildInfo = emitUsingBuildInfo; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); var moduleKind = ts.getEmitModuleKind(printerOptions); @@ -103229,8 +103735,10 @@ var ts; var detachedCommentsInfo; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; - var _a = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _a.enter, exitComment = _a.exit; - var preprint = createPreprinter(handlers); + var lastSubstitution; + var currentParenthesizerRule; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + var parenthesizer = ts.factory.parenthesizer; var emitBinaryExpression = createEmitBinaryExpression(); reset(); return { @@ -103430,7 +103938,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - emit(preprint(hint, node)); + pipelineEmit(hint, node, /*parenthesizerRule*/ undefined); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -103463,13 +103971,40 @@ var ts; function getCurrentLineMap() { return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } - function emit(node) { + function emit(node, parenthesizerRule) { if (node === undefined) return; var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - emitWithContext(node, emitWorker); + pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); } + function emitIdentifierName(node) { + if (node === undefined) + return; + pipelineEmit(2 /* IdentifierName */, node, /*parenthesizerRule*/ undefined); + } + function emitExpression(node, parenthesizerRule) { + if (node === undefined) + return; + pipelineEmit(1 /* Expression */, node, parenthesizerRule); + } + function emitJsxAttributeValue(node) { + pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); + } + function beforeEmitNode(node) { + if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { + preserveSourceNewlines = false; + } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; + var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); + pipelinePhase(emitHint, node); + currentParenthesizerRule = undefined; + } function shouldEmitComments(node) { return !commentsDisabled && !ts.isSourceFile(node); } @@ -103480,484 +104015,504 @@ var ts; !ts.isUnparsedSource(node) && !ts.isUnparsedPrepend(node); } - function beforeEmitWithContext(node, shouldEmitComments, shouldEmitSourceMaps) { - onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); - var emitFlags = ts.getEmitFlags(node); - var commentRange = shouldEmitComments ? ts.getCommentRange(node) : undefined; - var sourceMapRange = shouldEmitSourceMaps ? ts.getSourceMapRange(node) : undefined; - if (preserveSourceNewlines && (emitFlags & 134217728 /* IgnoreSourceNewlines */)) { - preserveSourceNewlines = false; - } - // Emit leading comments - if (commentRange) { - emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = true; - } - } - // Emit leading sourcemap - if (sourceMapRange) { - if (ts.isUnparsedNode(node)) { - ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); - var parsed = getParsedSourceMap(node.parent); - if (parsed && sourceMapGenerator) { - sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); + function getPipelinePhase(phase, emitHint, node) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { + return pipelineEmitWithNotification; } - } - else { - var source = sourceMapRange.source || sourceMapSource; - if (node.kind !== 339 /* NotEmittedStatement */ - && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && sourceMapRange.pos >= 0) { - emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + // falls through + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } + return pipelineEmitWithSubstitution; } - if (emitFlags & 64 /* NoNestedSourceMaps */) { - sourceMapsDisabled = true; + // falls through + case 2 /* Comments */: + if (shouldEmitComments(node)) { + return pipelineEmitWithComments; } - } + // falls through + case 3 /* SourceMaps */: + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; + } + // falls through + case 4 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase); } } - function afterEmitWithContext(node, shouldEmitComments, shouldEmitSourceMaps, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines) { - var emitFlags = ts.getEmitFlags(node); - var commentRange = shouldEmitComments ? ts.getCommentRange(node) : undefined; - var sourceMapRange = shouldEmitSourceMaps ? ts.getSourceMapRange(node) : undefined; - // Emit trailing sourcemap - if (sourceMapRange) { - if (!ts.isUnparsedNode(node)) { - if (emitFlags & 64 /* NoNestedSourceMaps */) { - sourceMapsDisabled = false; - } - if (node.kind !== 339 /* NotEmittedStatement */ - && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && sourceMapRange.end >= 0) { - emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); - } - } + function getNextPipelinePhase(currentPhase, emitHint, node) { + return getPipelinePhase(currentPhase + 1, emitHint, node); + } + function pipelineEmitWithNotification(hint, node) { + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + var savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); } - // Emit trailing comments - if (commentRange) { - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = false; - } - emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + else { + pipelineEmitWithHintWorker(hint, node); } - preserveSourceNewlines = savedPreserveSourceNewlines; onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + // clear the parenthesizer rule as we ascend + currentParenthesizerRule = undefined; } - function emitWithContext(node, emitCallback) { - var savedPreserveSourceNewlines = preserveSourceNewlines; - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; - var emitComments = shouldEmitComments(node); - var emitSourceMaps = shouldEmitSourceMaps(node); - beforeEmitWithContext(node, emitComments, emitSourceMaps); - emitCallback(node); - afterEmitWithContext(node, emitComments, emitSourceMaps, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines); - } - function emitWorker(node) { - switch (node.kind) { - // Literals - case 8 /* NumericLiteral */: - case 9 /* BigIntLiteral */: - return emitNumericOrBigIntLiteral(node); - case 10 /* StringLiteral */: - case 13 /* RegularExpressionLiteral */: - case 14 /* NoSubstitutionTemplateLiteral */: - return emitLiteral(node, /*jsxAttributeEscape*/ false); - case 11 /* JsxText */: - return emitJsxText(node); - // Pseudo-literals - case 15 /* TemplateHead */: - case 16 /* TemplateMiddle */: - case 17 /* TemplateTail */: - return emitLiteral(node, /*jsxAttributeEscape*/ false); - // Identifiers and PrivateIdentifiers - case 78 /* Identifier */: - return emitIdentifier(node); - case 79 /* PrivateIdentifier */: - return emitPrivateIdentifier(node); - // Names - case 158 /* QualifiedName */: - return emitQualifiedName(node); - case 159 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - // Signature elements - case 160 /* TypeParameter */: - return emitTypeParameter(node); - case 161 /* Parameter */: - return emitParameter(node); - case 162 /* Decorator */: - return emitDecorator(node); - // Type members - case 163 /* PropertySignature */: - return emitPropertySignature(node); - case 164 /* PropertyDeclaration */: - return emitPropertyDeclaration(node); - case 165 /* MethodSignature */: - return emitMethodSignature(node); - case 166 /* MethodDeclaration */: - return emitMethodDeclaration(node); - case 167 /* Constructor */: - return emitConstructor(node); - case 168 /* GetAccessor */: - case 169 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 170 /* CallSignature */: - return emitCallSignature(node); - case 171 /* ConstructSignature */: - return emitConstructSignature(node); - case 172 /* IndexSignature */: - return emitIndexSignature(node); - // Types - case 173 /* TypePredicate */: - return emitTypePredicate(node); - case 174 /* TypeReference */: - return emitTypeReference(node); - case 175 /* FunctionType */: - return emitFunctionType(node); - case 176 /* ConstructorType */: - return emitConstructorType(node); - case 177 /* TypeQuery */: - return emitTypeQuery(node); - case 178 /* TypeLiteral */: - return emitTypeLiteral(node); - case 179 /* ArrayType */: - return emitArrayType(node); - case 180 /* TupleType */: - return emitTupleType(node); - case 181 /* OptionalType */: - return emitOptionalType(node); - // SyntaxKind.RestType is handled below - case 183 /* UnionType */: - return emitUnionType(node); - case 184 /* IntersectionType */: - return emitIntersectionType(node); - case 185 /* ConditionalType */: - return emitConditionalType(node); - case 186 /* InferType */: - return emitInferType(node); - case 187 /* ParenthesizedType */: - return emitParenthesizedType(node); - case 188 /* ThisType */: - return emitThisType(); - case 189 /* TypeOperator */: - return emitTypeOperator(node); - case 190 /* IndexedAccessType */: - return emitIndexedAccessType(node); - case 191 /* MappedType */: - return emitMappedType(node); - case 192 /* LiteralType */: - return emitLiteralType(node); - case 193 /* NamedTupleMember */: - return emitNamedTupleMember(node); - case 194 /* TemplateLiteralType */: - return emitTemplateType(node); - case 195 /* TemplateLiteralTypeSpan */: - return emitTemplateTypeSpan(node); - case 196 /* ImportType */: - return emitImportTypeNode(node); - // Binding patterns - case 197 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 198 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 199 /* BindingElement */: - return emitBindingElement(node); - // Expressions - case 200 /* ArrayLiteralExpression */: - return emitArrayLiteralExpression(node); - case 201 /* ObjectLiteralExpression */: - return emitObjectLiteralExpression(node); - case 202 /* PropertyAccessExpression */: - return emitPropertyAccessExpression(node); - case 203 /* ElementAccessExpression */: - return emitElementAccessExpression(node); - case 204 /* CallExpression */: - return emitCallExpression(node); - case 205 /* NewExpression */: - return emitNewExpression(node); - case 206 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 207 /* TypeAssertionExpression */: - return emitTypeAssertionExpression(node); - case 208 /* ParenthesizedExpression */: - return emitParenthesizedExpression(node); - case 209 /* FunctionExpression */: - return emitFunctionExpression(node); - case 210 /* ArrowFunction */: - return emitArrowFunction(node); - case 211 /* DeleteExpression */: - return emitDeleteExpression(node); - case 212 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 213 /* VoidExpression */: - return emitVoidExpression(node); - case 214 /* AwaitExpression */: - return emitAwaitExpression(node); - case 215 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 216 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 217 /* BinaryExpression */: - return emitBinaryExpression(node); - case 218 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 219 /* TemplateExpression */: - return emitTemplateExpression(node); - case 220 /* YieldExpression */: - return emitYieldExpression(node); - case 221 /* SpreadElement */: - return emitSpreadExpression(node); - case 222 /* ClassExpression */: - return emitClassExpression(node); - case 223 /* OmittedExpression */: - return; - case 224 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(node); - case 225 /* AsExpression */: - return emitAsExpression(node); - case 226 /* NonNullExpression */: - return emitNonNullExpression(node); - case 227 /* MetaProperty */: - return emitMetaProperty(node); - case 228 /* SyntheticExpression */: - ts.Debug.fail("SyntheticExpression should never be printed."); - break; - // Misc - case 229 /* TemplateSpan */: - return emitTemplateSpan(node); - case 230 /* SemicolonClassElement */: - return emitSemicolonClassElement(); - // Element - case 231 /* Block */: - return emitBlock(node); - case 232 /* EmptyStatement */: - return emitEmptyStatement(/*isEmbeddedStatement*/ false); - case 233 /* VariableStatement */: - return emitVariableStatement(node); - case 234 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 235 /* IfStatement */: - return emitIfStatement(node); - case 236 /* DoStatement */: - return emitDoStatement(node); - case 237 /* WhileStatement */: - return emitWhileStatement(node); - case 238 /* ForStatement */: - return emitForStatement(node); - case 239 /* ForInStatement */: - return emitForInStatement(node); - case 240 /* ForOfStatement */: - return emitForOfStatement(node); - case 241 /* ContinueStatement */: - return emitContinueStatement(node); - case 242 /* BreakStatement */: - return emitBreakStatement(node); - case 243 /* ReturnStatement */: - return emitReturnStatement(node); - case 244 /* WithStatement */: - return emitWithStatement(node); - case 245 /* SwitchStatement */: - return emitSwitchStatement(node); - case 246 /* LabeledStatement */: - return emitLabeledStatement(node); - case 247 /* ThrowStatement */: - return emitThrowStatement(node); - case 248 /* TryStatement */: - return emitTryStatement(node); - case 249 /* DebuggerStatement */: - return emitDebuggerStatement(node); - // Declarations - case 250 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 251 /* VariableDeclarationList */: - return emitVariableDeclarationList(node); - case 252 /* FunctionDeclaration */: - return emitFunctionDeclaration(node); - case 253 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 254 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 255 /* TypeAliasDeclaration */: - return emitTypeAliasDeclaration(node); - case 256 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 257 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 258 /* ModuleBlock */: - return emitModuleBlock(node); - case 259 /* CaseBlock */: - return emitCaseBlock(node); - case 260 /* NamespaceExportDeclaration */: - return emitNamespaceExportDeclaration(node); - case 261 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 262 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 263 /* ImportClause */: - return emitImportClause(node); - case 264 /* NamespaceImport */: - return emitNamespaceImport(node); - case 265 /* NamedImports */: - return emitNamedImports(node); - case 266 /* ImportSpecifier */: - return emitImportSpecifier(node); - case 267 /* ExportAssignment */: - return emitExportAssignment(node); - case 268 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 269 /* NamedExports */: - return emitNamedExports(node); - case 270 /* NamespaceExport */: - return emitNamespaceExport(node); - case 271 /* ExportSpecifier */: - return emitExportSpecifier(node); - case 272 /* MissingDeclaration */: - return; - // Module references - case 273 /* ExternalModuleReference */: - return emitExternalModuleReference(node); - // JSX - case 274 /* JsxElement */: - return emitJsxElement(node); - case 275 /* JsxSelfClosingElement */: - return emitJsxSelfClosingElement(node); - case 278 /* JsxFragment */: - return emitJsxFragment(node); - case 276 /* JsxOpeningElement */: - case 279 /* JsxOpeningFragment */: - return emitJsxOpeningElementOrFragment(node); - case 277 /* JsxClosingElement */: - case 280 /* JsxClosingFragment */: - return emitJsxClosingElementOrFragment(node); - case 281 /* JsxAttribute */: - return emitJsxAttribute(node); - case 282 /* JsxAttributes */: - return emitJsxAttributes(node); - case 283 /* JsxSpreadAttribute */: - return emitJsxSpreadAttribute(node); - case 284 /* JsxExpression */: - return emitJsxExpression(node); - // Clauses - case 285 /* CaseClause */: - return emitCaseClause(node); - case 286 /* DefaultClause */: - return emitDefaultClause(node); - case 287 /* HeritageClause */: - return emitHeritageClause(node); - case 288 /* CatchClause */: - return emitCatchClause(node); - // Property assignments - case 289 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 290 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 291 /* SpreadAssignment */: - return emitSpreadAssignment(node); - // Enum - case 292 /* EnumMember */: - return emitEnumMember(node); - // Unparsed - case 293 /* UnparsedPrologue */: - return writeUnparsedNode(node); - case 300 /* UnparsedSource */: - case 294 /* UnparsedPrepend */: - return emitUnparsedSourceOrPrepend(node); - case 295 /* UnparsedText */: - case 296 /* UnparsedInternalText */: - return emitUnparsedTextLike(node); - case 297 /* UnparsedSyntheticReference */: - return emitUnparsedSyntheticReference(node); - // Top-level nodes - case 298 /* SourceFile */: - return emitSourceFile(node); - case 299 /* Bundle */: - ts.Debug.fail("Bundles should be printed using printBundle"); - break; - // SyntaxKind.UnparsedSource (handled above) - case 301 /* InputFiles */: - ts.Debug.fail("InputFiles should not be printed"); - break; - // JSDoc nodes (only used in codefixes currently) - case 302 /* JSDocTypeExpression */: - return emitJSDocTypeExpression(node); - case 303 /* JSDocNameReference */: - return emitJSDocNameReference(node); - case 304 /* JSDocAllType */: - return writePunctuation("*"); - case 305 /* JSDocUnknownType */: - return writePunctuation("?"); - case 306 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 307 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 308 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 309 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 182 /* RestType */: - case 310 /* JSDocVariadicType */: - return emitRestOrJSDocVariadicType(node); - // SyntaxKind.JSDocNamepathType (missing) - case 312 /* JSDocComment */: - return emitJSDoc(node); - case 314 /* JSDocTypeLiteral */: - return emitJSDocTypeLiteral(node); - case 315 /* JSDocSignature */: - return emitJSDocSignature(node); - case 317 /* JSDocTag */: - case 322 /* JSDocClassTag */: - return emitJSDocSimpleTag(node); - case 318 /* JSDocAugmentsTag */: - case 319 /* JSDocImplementsTag */: - return emitJSDocHeritageTag(node); - // SyntaxKind.JSDocAuthorTag (missing) - // SyntaxKind.JSDocDeprecatedTag (missing) - // SyntaxKind.JSDocClassTag (see JSDocTag, above) - // SyntaxKind.JSDocPublicTag (missing) - // SyntaxKind.JSDocPrivateTag (missing) - // SyntaxKind.JSDocProtectedTag (missing) - // SyntaxKind.JSDocReadonlyTag (missing) - case 328 /* JSDocCallbackTag */: - return emitJSDocCallbackTag(node); - // SyntaxKind.JSDocEnumTag (see below) - case 330 /* JSDocParameterTag */: - case 337 /* JSDocPropertyTag */: - return emitJSDocPropertyLikeTag(node); - case 329 /* JSDocEnumTag */: - case 331 /* JSDocReturnTag */: - case 332 /* JSDocThisTag */: - case 333 /* JSDocTypeTag */: - return emitJSDocSimpleTypedTag(node); - case 334 /* JSDocTemplateTag */: - return emitJSDocTemplateTag(node); - case 335 /* JSDocTypedefTag */: - return emitJSDocTypedefTag(node); - case 336 /* JSDocSeeTag */: - return emitJSDocSeeTag(node); - // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) - // Synthesized list - case 338 /* SyntaxList */: - ts.Debug.fail("SyntaxList should not be printed"); - break; - // Transformation nodes - case 339 /* NotEmittedStatement */: - break; - case 340 /* PartiallyEmittedExpression */: - return emitPartiallyEmittedExpression(node); - case 341 /* CommaListExpression */: - return emitCommaList(node); - case 342 /* MergeDeclarationMarker */: - case 343 /* EndOfDeclarationMarker */: - break; - case 344 /* SyntheticReferenceExpression */: - ts.Debug.fail("SyntheticReferenceExpression should not be printed"); + function pipelineEmitWithHintWorker(hint, node) { + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 6 /* JsxAttributeValue */) + return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } + if (hint === 4 /* Unspecified */) { + switch (node.kind) { + // Pseudo-literals + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return emitLiteral(node, /*jsxAttributeEscape*/ false); + // Identifiers + case 78 /* Identifier */: + return emitIdentifier(node); + // PrivateIdentifiers + case 79 /* PrivateIdentifier */: + return emitPrivateIdentifier(node); + // Parse tree nodes + // Names + case 158 /* QualifiedName */: + return emitQualifiedName(node); + case 159 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 160 /* TypeParameter */: + return emitTypeParameter(node); + case 161 /* Parameter */: + return emitParameter(node); + case 162 /* Decorator */: + return emitDecorator(node); + // Type members + case 163 /* PropertySignature */: + return emitPropertySignature(node); + case 164 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 165 /* MethodSignature */: + return emitMethodSignature(node); + case 166 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 167 /* Constructor */: + return emitConstructor(node); + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 170 /* CallSignature */: + return emitCallSignature(node); + case 171 /* ConstructSignature */: + return emitConstructSignature(node); + case 172 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 173 /* TypePredicate */: + return emitTypePredicate(node); + case 174 /* TypeReference */: + return emitTypeReference(node); + case 175 /* FunctionType */: + return emitFunctionType(node); + case 176 /* ConstructorType */: + return emitConstructorType(node); + case 177 /* TypeQuery */: + return emitTypeQuery(node); + case 178 /* TypeLiteral */: + return emitTypeLiteral(node); + case 179 /* ArrayType */: + return emitArrayType(node); + case 180 /* TupleType */: + return emitTupleType(node); + case 181 /* OptionalType */: + return emitOptionalType(node); + // SyntaxKind.RestType is handled below + case 183 /* UnionType */: + return emitUnionType(node); + case 184 /* IntersectionType */: + return emitIntersectionType(node); + case 185 /* ConditionalType */: + return emitConditionalType(node); + case 186 /* InferType */: + return emitInferType(node); + case 187 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 224 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 188 /* ThisType */: + return emitThisType(); + case 189 /* TypeOperator */: + return emitTypeOperator(node); + case 190 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 191 /* MappedType */: + return emitMappedType(node); + case 192 /* LiteralType */: + return emitLiteralType(node); + case 193 /* NamedTupleMember */: + return emitNamedTupleMember(node); + case 194 /* TemplateLiteralType */: + return emitTemplateType(node); + case 195 /* TemplateLiteralTypeSpan */: + return emitTemplateTypeSpan(node); + case 196 /* ImportType */: + return emitImportTypeNode(node); + // Binding patterns + case 197 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 198 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 199 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 229 /* TemplateSpan */: + return emitTemplateSpan(node); + case 230 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 231 /* Block */: + return emitBlock(node); + case 233 /* VariableStatement */: + return emitVariableStatement(node); + case 232 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 234 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 235 /* IfStatement */: + return emitIfStatement(node); + case 236 /* DoStatement */: + return emitDoStatement(node); + case 237 /* WhileStatement */: + return emitWhileStatement(node); + case 238 /* ForStatement */: + return emitForStatement(node); + case 239 /* ForInStatement */: + return emitForInStatement(node); + case 240 /* ForOfStatement */: + return emitForOfStatement(node); + case 241 /* ContinueStatement */: + return emitContinueStatement(node); + case 242 /* BreakStatement */: + return emitBreakStatement(node); + case 243 /* ReturnStatement */: + return emitReturnStatement(node); + case 244 /* WithStatement */: + return emitWithStatement(node); + case 245 /* SwitchStatement */: + return emitSwitchStatement(node); + case 246 /* LabeledStatement */: + return emitLabeledStatement(node); + case 247 /* ThrowStatement */: + return emitThrowStatement(node); + case 248 /* TryStatement */: + return emitTryStatement(node); + case 249 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 250 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 251 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 252 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 253 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 254 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 255 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 256 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 257 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 258 /* ModuleBlock */: + return emitModuleBlock(node); + case 259 /* CaseBlock */: + return emitCaseBlock(node); + case 260 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 261 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 262 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 263 /* ImportClause */: + return emitImportClause(node); + case 264 /* NamespaceImport */: + return emitNamespaceImport(node); + case 270 /* NamespaceExport */: + return emitNamespaceExport(node); + case 265 /* NamedImports */: + return emitNamedImports(node); + case 266 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 267 /* ExportAssignment */: + return emitExportAssignment(node); + case 268 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 269 /* NamedExports */: + return emitNamedExports(node); + case 271 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 272 /* MissingDeclaration */: + return; + // Module references + case 273 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 11 /* JsxText */: + return emitJsxText(node); + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 277 /* JsxClosingElement */: + case 280 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 281 /* JsxAttribute */: + return emitJsxAttribute(node); + case 282 /* JsxAttributes */: + return emitJsxAttributes(node); + case 283 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 284 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 285 /* CaseClause */: + return emitCaseClause(node); + case 286 /* DefaultClause */: + return emitDefaultClause(node); + case 287 /* HeritageClause */: + return emitHeritageClause(node); + case 288 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 289 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 290 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 291 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 292 /* EnumMember */: + return emitEnumMember(node); + // Unparsed + case 293 /* UnparsedPrologue */: + return writeUnparsedNode(node); + case 300 /* UnparsedSource */: + case 294 /* UnparsedPrepend */: + return emitUnparsedSourceOrPrepend(node); + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: + return emitUnparsedTextLike(node); + case 297 /* UnparsedSyntheticReference */: + return emitUnparsedSyntheticReference(node); + // Top-level nodes + case 298 /* SourceFile */: + return emitSourceFile(node); + case 299 /* Bundle */: + return ts.Debug.fail("Bundles should be printed using printBundle"); + // SyntaxKind.UnparsedSource (handled above) + case 301 /* InputFiles */: + return ts.Debug.fail("InputFiles should not be printed"); + // JSDoc nodes (only used in codefixes currently) + case 302 /* JSDocTypeExpression */: + return emitJSDocTypeExpression(node); + case 303 /* JSDocNameReference */: + return emitJSDocNameReference(node); + case 304 /* JSDocAllType */: + return writePunctuation("*"); + case 305 /* JSDocUnknownType */: + return writePunctuation("?"); + case 306 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 307 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 308 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 309 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 182 /* RestType */: + case 310 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + case 311 /* JSDocNamepathType */: + return; + case 312 /* JSDocComment */: + return emitJSDoc(node); + case 314 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 315 /* JSDocSignature */: + return emitJSDocSignature(node); + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + return emitJSDocSimpleTag(node); + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + return emitJSDocHeritageTag(node); + case 320 /* JSDocAuthorTag */: + case 321 /* JSDocDeprecatedTag */: + return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 327 /* JSDocOverrideTag */: + return; + case 328 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + // SyntaxKind.JSDocEnumTag (see below) + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 329 /* JSDocEnumTag */: + case 331 /* JSDocReturnTag */: + case 332 /* JSDocThisTag */: + case 333 /* JSDocTypeTag */: + return emitJSDocSimpleTypedTag(node); + case 334 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 335 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 336 /* JSDocSeeTag */: + return emitJSDocSeeTag(node); + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) + // Transformation nodes + case 339 /* NotEmittedStatement */: + case 343 /* EndOfDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: + return; + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + if (substituteNode !== ts.noEmitSubstitution) { + var substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } + } + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node, /*jsxAttributeEscape*/ false); + // Identifiers + case 78 /* Identifier */: + return emitIdentifier(node); + // Expressions + case 200 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 201 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 202 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 203 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 204 /* CallExpression */: + return emitCallExpression(node); + case 205 /* NewExpression */: + return emitNewExpression(node); + case 206 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 207 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 208 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 209 /* FunctionExpression */: + return emitFunctionExpression(node); + case 210 /* ArrowFunction */: + return emitArrowFunction(node); + case 211 /* DeleteExpression */: + return emitDeleteExpression(node); + case 212 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 213 /* VoidExpression */: + return emitVoidExpression(node); + case 214 /* AwaitExpression */: + return emitAwaitExpression(node); + case 215 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 216 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 217 /* BinaryExpression */: + return emitBinaryExpression(node); + case 218 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 219 /* TemplateExpression */: + return emitTemplateExpression(node); + case 220 /* YieldExpression */: + return emitYieldExpression(node); + case 221 /* SpreadElement */: + return emitSpreadElement(node); + case 222 /* ClassExpression */: + return emitClassExpression(node); + case 223 /* OmittedExpression */: + return; + case 225 /* AsExpression */: + return emitAsExpression(node); + case 226 /* NonNullExpression */: + return emitNonNullExpression(node); + case 227 /* MetaProperty */: + return emitMetaProperty(node); + case 228 /* SyntheticExpression */: + return ts.Debug.fail("SyntheticExpression should never be printed."); + // JSX + case 274 /* JsxElement */: + return emitJsxElement(node); + case 275 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 278 /* JsxFragment */: + return emitJsxFragment(node); + // Synthesized list + case 338 /* SyntaxList */: + return ts.Debug.fail("SyntaxList should not be printed"); + // Transformation nodes + case 339 /* NotEmittedStatement */: + return; + case 340 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 341 /* CommaListExpression */: + return emitCommaList(node); + case 342 /* MergeDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: + return; + case 344 /* SyntheticReferenceExpression */: + return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); + } } if (ts.isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); if (ts.isTokenKind(node.kind)) return writeTokenNode(node, writePunctuation); + ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); } function emitMappedTypeParameter(node) { emit(node.name); @@ -103966,6 +104521,13 @@ var ts; writeSpace(); emit(node.constraint); } + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node); + ts.Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); + } function getHelpersFromBundledSourceFiles(bundle) { var result; if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) { @@ -104068,9 +104630,6 @@ var ts; writeStringLiteral(text); } } - function emitStringLiteralWithJsxAttributeEscape(node) { - emitLiteral(node, /*jsxAttributeEscape*/ true); - } // SyntaxKind.UnparsedSource // SyntaxKind.UnparsedPrepend function emitUnparsedSourceOrPrepend(unparsed) { @@ -104129,7 +104688,7 @@ var ts; } function emitEntityName(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -104137,7 +104696,7 @@ var ts; } function emitComputedPropertyName(node) { writePunctuation("["); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } // @@ -104171,11 +104730,11 @@ 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); + 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); } function emitDecorator(decorator) { writePunctuation("@"); - emit(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } // // Type members @@ -104340,7 +104899,7 @@ var ts; writePunctuation("}"); } function emitArrayType(node) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -104363,21 +104922,21 @@ var ts; emit(node.type); } function emitOptionalType(node) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 516 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node) { - emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -104403,10 +104962,10 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -104429,7 +104988,7 @@ var ts; writeSpace(); } writePunctuation("["); - emitWithContext(node.typeParameter, emitMappedTypeParameter); + pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter); if (node.nameType) { writeSpace(); writeKeyword("as"); @@ -104457,7 +105016,7 @@ var ts; writePunctuation("}"); } function emitLiteralType(node) { - emit(node.literal); + emitExpression(node.literal); } function emitTemplateType(node) { emit(node.head); @@ -104499,7 +105058,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // Expressions @@ -104507,7 +105066,7 @@ var ts; function emitArrayLiteralExpression(node) { var elements = node.elements; var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; - emitList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -104523,7 +105082,7 @@ var ts; } } function emitPropertyAccessExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos); var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); var linesAfterDot = getLinesBetweenNodes(node, token, node.name); @@ -104565,41 +105124,41 @@ var ts; } } function emitElementAccessExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); - emit(node.argumentExpression); + emitExpression(node.argumentExpression); emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitList(node, node.arguments, 2576 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitList(node, node.arguments, 18960 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node) { - emit(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); - emit(node.template); + emitExpression(node.template); } function emitTypeAssertionExpression(node) { writePunctuation("<"); emit(node.type); writePunctuation(">"); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emit(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -104623,29 +105182,29 @@ var ts; function emitDeleteExpression(node) { emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node) { writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emit(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node) { // In some cases, we need to emit a space between the operator and the operand. One obvious case @@ -104666,11 +105225,11 @@ var ts; || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { - emit(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } function createEmitBinaryExpression() { - return ts.createBinaryExpressionTrampoline(onEnter, maybeEmitExpression, onOperator, maybeEmitExpression, onExit, /*foldState*/ undefined); + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); function onEnter(node, state) { if (state) { state.stackIndex++; @@ -104680,7 +105239,12 @@ var ts; state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); - beforeEmitWithContext(node, emitComments_1, emitSourceMaps); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (emitComments_1) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); } else { state = { @@ -104695,6 +105259,9 @@ var ts; } return state; } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } function onOperator(operatorToken, _state, node) { var isCommaOperator = operatorToken.kind !== 27 /* CommaToken */; var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); @@ -104705,6 +105272,9 @@ var ts; emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } function onExit(node, state) { var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); @@ -104716,16 +105286,35 @@ var ts; var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex]; var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex]; - afterEmitWithContext(node, shouldEmitComments_1, shouldEmitSourceMaps_1, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines); + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps_1) + emitSourceMapsAfterNode(node); + if (shouldEmitComments_1) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); state.stackIndex--; } } - function maybeEmitExpression(next) { - // Push a new frame for binary expressions, otherwise emit all other expressions. - if (ts.isBinaryExpression(next)) { - return next; + function maybeEmitExpression(next, parent, side) { + var parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); + var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next); + if (pipelinePhase === pipelineEmitWithSubstitution) { + ts.Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression)); + pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next); + lastSubstitution = undefined; } - emit(next); + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (ts.isBinaryExpression(next)) { + return next; + } + } + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1 /* Expression */, next); } } function emitConditionalExpression(node) { @@ -104733,16 +105322,16 @@ var ts; var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emit(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true); - emit(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true); - emit(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { @@ -104752,22 +105341,22 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node) { + function emitSpreadElement(node) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emit(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -104776,7 +105365,7 @@ var ts; } } function emitNonNullExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } function emitMetaProperty(node) { @@ -104788,7 +105377,7 @@ var ts; // Misc // function emitTemplateSpan(node) { - emit(node.expression); + emitExpression(node.expression); emit(node.literal); } // @@ -104818,11 +105407,8 @@ var ts; writeTrailingSemicolon(); } } - function emitEmbeddedEmptyStatement(_node) { - emitEmptyStatement(/*isEmbeddedStatement*/ true); - } function emitExpressionStatement(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); // Emit semicolon in non json files // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { @@ -104833,7 +105419,7 @@ var ts; var openParenPos = emitTokenWithComment(98 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { @@ -104852,7 +105438,7 @@ var ts; var openParenPos = emitTokenWithComment(114 /* WhileKeyword */, startPos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); } function emitDoStatement(node) { @@ -104891,7 +105477,7 @@ var ts; writeSpace(); emitTokenWithComment(100 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -104904,7 +105490,7 @@ var ts; writeSpace(); emitTokenWithComment(157 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -104914,7 +105500,7 @@ var ts; emit(node); } else { - emit(node); + emitExpression(node); } } } @@ -104961,7 +105547,7 @@ var ts; var openParenPos = emitTokenWithComment(115 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -104969,7 +105555,7 @@ var ts; var openParenPos = emitTokenWithComment(106 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); @@ -105011,7 +105597,7 @@ var ts; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); @@ -105027,7 +105613,7 @@ var ts; writeKeyword("function"); emit(node.asteriskToken); writeSpace(); - emit(node.name); + emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } function emitSignatureAndBody(node, emitSignatureHead) { @@ -105051,7 +105637,7 @@ var ts; else { emitSignatureHead(node); writeSpace(); - emit(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -105126,7 +105712,7 @@ var ts; increaseIndent(); } else { - emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, /*parenthesizerRule*/ undefined, statementOffset); } } function emitClassDeclaration(node) { @@ -105139,7 +105725,7 @@ var ts; writeKeyword("class"); if (node.name) { writeSpace(); - emit(node.name); + emitIdentifierName(node.name); } var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { @@ -105237,7 +105823,7 @@ var ts; } function emitModuleReference(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -105253,7 +105839,7 @@ var ts; emitTokenWithComment(153 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } - emit(node.moduleSpecifier); + emitExpression(node.moduleSpecifier); writeTrailingSemicolon(); } function emitImportClause(node) { @@ -105291,7 +105877,9 @@ var ts; emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); - emit(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(62 /* EqualsToken */) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -105312,7 +105900,7 @@ var ts; var fromPos = node.exportClause ? node.exportClause.end : nextPos; emitTokenWithComment(153 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); - emit(node.moduleSpecifier); + emitExpression(node.moduleSpecifier); } writeTrailingSemicolon(); } @@ -105359,7 +105947,7 @@ var ts; function emitExternalModuleReference(node) { writeKeyword("require"); writePunctuation("("); - emit(node.expression); + emitExpression(node.expression); writePunctuation(")"); } // @@ -105411,17 +105999,13 @@ var ts; function emitJsxAttributes(node) { emitList(node, node.properties, 262656 /* JsxElementAttributes */); } - function emitJsxAttributeValue(node) { - var emitCallback = ts.isStringLiteral(node) ? emitStringLiteralWithJsxAttributeEscape : emitWorker; - emitWithContext(node, emitCallback); - } function emitJsxAttribute(node) { emit(node.name); emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue); } function emitJsxSpreadAttribute(node) { writePunctuation("{..."); - emit(node.expression); + emitExpression(node.expression); writePunctuation("}"); } function hasTrailingCommentsAtPosition(pos) { @@ -105446,7 +106030,7 @@ var ts; } var end = emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); emit(node.dotDotDotToken); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(19 /* CloseBraceToken */, ((_a = node.expression) === null || _a === void 0 ? void 0 : _a.end) || end, writePunctuation, node); if (isMultiline) { writer.decreaseIndent(); @@ -105455,7 +106039,7 @@ var ts; } function emitJsxTagName(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -105467,7 +106051,7 @@ var ts; function emitCaseClause(node) { emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { @@ -105528,7 +106112,7 @@ var ts; var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emit(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node) { emit(node.name); @@ -105536,13 +106120,13 @@ var ts; writeSpace(); writePunctuation("="); writeSpace(); - emit(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node) { if (node.expression) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } // @@ -105550,7 +106134,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // JSDoc @@ -105795,15 +106379,15 @@ var ts; emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + emitList(node, statements, 1 /* MultiLine */, /*parenthesizerRule*/ undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } // Transformation nodes function emitPartiallyEmittedExpression(node) { - emit(node.expression); + emitExpression(node.expression); } function emitCommaList(node) { - emitList(node, node.elements, 528 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -105949,12 +106533,12 @@ var ts; emit(node); } } - function emitInitializer(node, equalCommentStartPos, container) { + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); - emit(node); + emitExpression(node, parenthesizerRule); } } function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { @@ -105969,10 +106553,10 @@ var ts; emit(node); } } - function emitExpressionWithLeadingSpace(node) { + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { if (node) { writeSpace(); - emit(node); + emitExpression(node, parenthesizerRule); } } function emitWithTrailingSpace(node) { @@ -105990,7 +106574,7 @@ var ts; writeLine(); increaseIndent(); if (ts.isEmptyStatement(node)) { - emitWithContext(node, emitEmbeddedEmptyStatement); + pipelineEmit(5 /* EmbeddedStatement */, node); } else { emit(node); @@ -106002,7 +106586,7 @@ var ts; emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures @@ -106063,7 +106647,13 @@ var ts; break; } } - function emitList(parentNode, children, format, start, count) { + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; @@ -106167,7 +106757,12 @@ var ts; shouldEmitInterveningComments = mayEmitInterveningComments; } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); shouldDecreaseIndentAfterEmit = false; @@ -106903,6 +107498,33 @@ var ts; return node; } // Comments + function pipelineEmitWithComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit leading comments + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit trailing comments + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; @@ -107198,6 +107820,50 @@ var ts; } return node.parsedSourceMap || undefined; } + function pipelineEmitWithSourceMaps(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node); + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit leading sourcemap + if (ts.isUnparsedNode(node)) { + ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); + var parsed = getParsedSourceMap(node.parent); + if (parsed && sourceMapGenerator) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); + } + } + else { + var source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 339 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + } + } + } + function emitSourceMapsAfterNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit trailing sourcemap + if (!ts.isUnparsedNode(node)) { + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = false; + } + if (node.kind !== 339 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); + } + } + } /** * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source */ @@ -107290,736 +107956,6 @@ var ts; } } ts.createPrinter = createPrinter; - var PreprintPipelinePhase; - (function (PreprintPipelinePhase) { - PreprintPipelinePhase[PreprintPipelinePhase["Notification"] = 0] = "Notification"; - PreprintPipelinePhase[PreprintPipelinePhase["Substitution"] = 1] = "Substitution"; - PreprintPipelinePhase[PreprintPipelinePhase["Visit"] = 2] = "Visit"; - })(PreprintPipelinePhase || (PreprintPipelinePhase = {})); - function createPreprinter(handlers) { - var _a = handlers.substituteNode, substituteNode = _a === void 0 ? ts.noEmitSubstitution : _a, _b = handlers.onEmitNode, onEmitNode = _b === void 0 ? ts.noEmitNotification : _b, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled; - var pipelineResult; - // Outer visitors - // - // These visitors are invoked by inner visitors to re-enter the pipeline - // for notification and substitution. - var visit = makeVisitor(pipelineVisitorForUnspecified); - var visitSourceFile = makeVisitor(pipelineVisitorForSourceFile, ts.isSourceFile); - var visitIdentifierName = makeVisitor(pipelineVisitorForIdentifierName, ts.isIdentifier); - var visitModuleName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isModuleName); - var visitPropertyName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isPropertyName); - var visitMemberName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isMemberName); - var visitBindingName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isBindingName); - var visitEntityName = makeVisitor(pipelineVisitorForIdentifierReferenceOrUnspecified, ts.isEntityName); - var visitExpression = makeVisitor(pipelineVisitorForExpression, ts.isExpression); - var visitForInitializer = makeVisitor(pipelineVisitorForForInitializer, ts.isForInitializer); - var visitTypeNode = makeVisitor(pipelineVisitorForUnspecified, ts.isTypeNode); - var visitEmbeddedStatement = makeVisitor(pipelineVisitorForEmbeddedStatement, ts.isStatement, ts.factory.liftToBlock); - var visitJsxAttributeValue = makeVisitor(pipelineVisitorForJsxAttributeValue, ts.isStringLiteralOrJsxExpression); - var visitMappedTypeParameter = makeVisitor(pipelineVisitorForMappedTypeParameter, ts.isTypeParameterDeclaration); - var visitConciseBody = makeVisitor(pipelineVisitorForConciseBody, ts.isConciseBody); - var visitFunctionBody = makeVisitor(pipelineVisitorForUnspecified, ts.isFunctionBody); - var visitList = makeListVisitor(pipelineVisitorForUnspecified); - var visitTypeNodeList = makeListVisitor(pipelineVisitorForUnspecified, ts.isTypeNode); - var visitExpressionList = makeListVisitor(pipelineVisitorForExpression, ts.isExpression); - var visitParameterList = makeListVisitor(pipelineVisitorForUnspecified, ts.isParameter); - function makeVisitor(outerVisitor, defaultTest, lift) { - function visit(node, test) { - return ts.visitNode(node, outerVisitor, test || defaultTest, lift); - } - return visit; - } - function makeListVisitor(outerVisitor, defaultTest) { - function visitList(nodes, test) { - if (test === void 0) { test = defaultTest || ts.returnTrue; } - return ts.visitNodes(nodes, outerVisitor, test); - } - return visitList; - } - // Pipeline Visitors - // - // These visitors execute our existing pipeline logic for notification and substitution, - // but adapted to our visitor pattern. In some cases, we refine the `EmitHint` we pass - // to the `onEmitNode` and `substituteNode` APIs to ensure they receive the appropriate - // context. - // - // For example, the ConciseBody of an arrow function could be an Identifier, in which - // case we would want to use `EmitHint.Expression` to ensure we treat the identifier - // as an expression during substitution. - function pipelineVisitorForSourceFile(node) { return pipelineVisitorWorker(0 /* SourceFile */, node); } - function pipelineVisitorForExpression(node) { return pipelineVisitorWorker(1 /* Expression */, node); } - function pipelineVisitorForIdentifierName(node) { return pipelineVisitorWorker(2 /* IdentifierName */, node); } - function pipelineVisitorForIdentifierNameOrUnspecified(node) { return pipelineVisitorWorker(ts.isIdentifier(node) ? 2 /* IdentifierName */ : 4 /* Unspecified */, node); } - function pipelineVisitorForIdentifierReferenceOrUnspecified(node) { return pipelineVisitorWorker(ts.isIdentifier(node) ? 1 /* Expression */ : 4 /* Unspecified */, node); } - function pipelineVisitorForForInitializer(node) { return pipelineVisitorWorker(ts.isVariableDeclarationList(node) ? 4 /* Unspecified */ : 1 /* Expression */, node); } - function pipelineVisitorForMappedTypeParameter(node) { return pipelineVisitorWorker(3 /* MappedTypeParameter */, node); } - function pipelineVisitorForEmbeddedStatement(node) { return pipelineVisitorWorker(ts.isEmptyStatement(node) ? 5 /* EmbeddedStatement */ : 4 /* Unspecified */, node); } - function pipelineVisitorForJsxAttributeValue(node) { return pipelineVisitorWorker(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); } - function pipelineVisitorForConciseBody(node) { return pipelineVisitorWorker(ts.isBlock(node) ? 4 /* Unspecified */ : 1 /* Expression */, node); } - function pipelineVisitorForUnspecified(node) { return pipelineVisitorWorker(4 /* Unspecified */, node); } - /** - * Adapts the emit pipeline API to work with the visitor API - */ - function pipelineVisitorWorker(hint, node) { - resetPipelineResult(); - // Get the first supported pipeline phase for this node and evaluate it. We can skip several stack - // frames if we aren't doing emit notification, so we check for substitution and direct callbacks - // and execute those immediately. - var pipelinePhase = getPipelinePhase(0 /* Notification */, node); - if (pipelinePhase === pipelineVisitDirect) { - return visitor(hint, node); - } - if (pipelinePhase === pipelineVisitWithSubstitution) { - // The next phase after substitution is always direct visitation, so we can reduce the call stack - // depth by calling the visitor directly. - return visitor(hint, substituteNode(hint, node)); - } - pipelinePhase(hint, node); - ts.Debug.assertIsDefined(pipelineResult); - var result = pipelineResult; - resetPipelineResult(); - return result; - } - function resetPipelineResult() { - pipelineResult = undefined; - } - /** - * Gets the pipeline callback to pass to the relevant API (i.e., `substituteNode` or `onEmitNode`) - */ - function getPipelinePhase(phase, node) { - switch (phase) { - case 0 /* Notification */: - if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { - return pipelineVisitWithNotification; - } - // falls through - case 1 /* Substitution */: - if (substituteNode !== ts.noEmitSubstitution) { - return pipelineVisitWithSubstitution; - } - // falls through - default: - return pipelineVisitDirect; - } - } - /** - * A callback that can be evaluated to trigger emit notification as part of the emit pipeline. - */ - function pipelineVisitWithNotification(hint, node) { - onEmitNode(hint, node, getPipelinePhase(1 /* Substitution */, node)); - } - /** - * A callback that can be evaluated to trigger JIT substitution as part of the emit pipeline. - */ - function pipelineVisitWithSubstitution(hint, node) { - // Next phase is always direct visitation, so we can reduce the call stack - // depth by calling the visitor directly. - pipelineResult = visitor(hint, substituteNode(hint, node)); - } - /** - * A callback that can be evaluated to visit the subtree of a node. - */ - function pipelineVisitDirect(hint, node) { - pipelineResult = visitor(hint, node); - } - /** - * Re-enters the visitor pattern from the pipeline pattern to perform - * tree updates and trigger parenthesization rules. - */ - function visitor(hint, node) { - // This should align with the assertions in `pipelineEmitWithHint`. - if (hint === 0 /* SourceFile */) - return preprintSourceFile(ts.cast(node, ts.isSourceFile)); - if (hint === 2 /* IdentifierName */) - return preprintIdentifier(ts.cast(node, ts.isIdentifier)); - if (hint === 6 /* JsxAttributeValue */) - return ts.cast(node, ts.isStringLiteral); - if (hint === 3 /* MappedTypeParameter */) - return preprintTypeParameterDeclaration(ts.cast(node, ts.isTypeParameterDeclaration)); - if (hint === 5 /* EmbeddedStatement */) - return ts.cast(node, ts.isEmptyStatement); - var kind = node.kind; - // No need to visit nodes without children. - if ((kind > 0 /* FirstToken */ && kind <= 157 /* LastToken */) || kind === 188 /* ThisType */) { - return node; - } - if (hint === 4 /* Unspecified */) { - if (ts.isKeyword(node.kind)) - return node; - switch (node.kind) { - // Identifiers - case 78 /* Identifier */: - return preprintIdentifier(node); - // Names - case 158 /* QualifiedName */: - ts.Debug.type(node); - return ts.factory.updateQualifiedName(node, visitEntityName(node.left), visitIdentifierName(node.right)); - case 159 /* ComputedPropertyName */: - ts.Debug.type(node); - return ts.factory.updateComputedPropertyName(node, visitExpression(node.expression)); - // Signature elements - case 160 /* TypeParameter */: - return preprintTypeParameterDeclaration(node); - case 161 /* Parameter */: - ts.Debug.type(node); - return ts.factory.updateParameterDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.dotDotDotToken, ts.isDotDotDotToken), visitBindingName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 162 /* Decorator */: - ts.Debug.type(node); - return ts.factory.updateDecorator(node, visitExpression(node.expression)); - // Type members - case 163 /* PropertySignature */: - ts.Debug.type(node); - return ts.factory.updatePropertySignature(node, visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type)); - case 164 /* PropertyDeclaration */: - ts.Debug.type(node); - return ts.factory.updatePropertyDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken || node.exclamationToken, ts.isQuestionOrExclamationToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 165 /* MethodSignature */: - ts.Debug.type(node); - return ts.factory.updateMethodSignature(node, visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 166 /* MethodDeclaration */: - ts.Debug.type(node); - return ts.factory.updateMethodDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 167 /* Constructor */: - ts.Debug.type(node); - return ts.factory.updateConstructorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitParameterList(node.parameters), visitFunctionBody(node.body)); - case 168 /* GetAccessor */: - ts.Debug.type(node); - return ts.factory.updateGetAccessorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 169 /* SetAccessor */: - ts.Debug.type(node); - return ts.factory.updateSetAccessorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visitParameterList(node.parameters), visitFunctionBody(node.body)); - case 170 /* CallSignature */: - ts.Debug.type(node); - return ts.factory.updateCallSignature(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 171 /* ConstructSignature */: - ts.Debug.type(node); - return ts.factory.updateConstructSignature(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 172 /* IndexSignature */: - ts.Debug.type(node); - return ts.factory.updateIndexSignature(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitParameterList(node.parameters), visitTypeNode(node.type)); - // Types - case 173 /* TypePredicate */: - ts.Debug.type(node); - return ts.factory.updateTypePredicateNode(node, visit(node.assertsModifier, ts.isAssertsKeyword), visit(node.parameterName, ts.isIdentifierOrThisTypeNode), visitTypeNode(node.type)); - case 174 /* TypeReference */: - ts.Debug.type(node); - return ts.factory.updateTypeReferenceNode(node, visitEntityName(node.typeName), visitTypeNodeList(node.typeArguments)); - case 175 /* FunctionType */: - ts.Debug.type(node); - return ts.factory.updateFunctionTypeNode(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), ts.visitNodes(node.parameters, pipelineVisitorForUnspecified, ts.isParameterDeclaration), visitTypeNode(node.type)); - case 176 /* ConstructorType */: - ts.Debug.type(node); - return ts.factory.updateConstructorTypeNode(node, ts.visitNodes(node.modifiers, pipelineVisitorForUnspecified, ts.isModifier), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 177 /* TypeQuery */: - ts.Debug.type(node); - return ts.factory.updateTypeQueryNode(node, visitEntityName(node.exprName)); - case 178 /* TypeLiteral */: - ts.Debug.type(node); - return ts.factory.updateTypeLiteralNode(node, visitList(node.members, ts.isTypeElement)); - case 179 /* ArrayType */: - ts.Debug.type(node); - return ts.factory.updateArrayTypeNode(node, visitTypeNode(node.elementType)); - case 180 /* TupleType */: - ts.Debug.type(node); - return ts.factory.updateTupleTypeNode(node, visitTypeNodeList(node.elements)); - case 181 /* OptionalType */: - ts.Debug.type(node); - return ts.factory.updateOptionalTypeNode(node, visitTypeNode(node.type)); - case 182 /* RestType */: - ts.Debug.type(node); - return ts.factory.updateRestTypeNode(node, visitTypeNode(node.type)); - case 183 /* UnionType */: - ts.Debug.type(node); - return ts.factory.updateUnionTypeNode(node, visitTypeNodeList(node.types)); - case 184 /* IntersectionType */: - ts.Debug.type(node); - return ts.factory.updateIntersectionTypeNode(node, visitTypeNodeList(node.types)); - case 185 /* ConditionalType */: - ts.Debug.type(node); - return ts.factory.updateConditionalTypeNode(node, visitTypeNode(node.checkType), visitTypeNode(node.extendsType), visitTypeNode(node.trueType), visitTypeNode(node.falseType)); - case 186 /* InferType */: - ts.Debug.type(node); - return ts.factory.updateInferTypeNode(node, visit(node.typeParameter, ts.isTypeParameterDeclaration)); - case 196 /* ImportType */: - ts.Debug.type(node); - return ts.factory.updateImportTypeNode(node, visitTypeNode(node.argument), visitEntityName(node.qualifier), visitTypeNodeList(node.typeArguments), node.isTypeOf); - case 193 /* NamedTupleMember */: - ts.Debug.type(node); - return ts.factory.updateNamedTupleMember(node, visit(node.dotDotDotToken, ts.isDotDotDotToken), visitIdentifierName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type)); - case 187 /* ParenthesizedType */: - ts.Debug.type(node); - return ts.factory.updateParenthesizedType(node, visitTypeNode(node.type)); - case 224 /* ExpressionWithTypeArguments */: - ts.Debug.type(node); - return ts.factory.updateExpressionWithTypeArguments(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments)); - case 189 /* TypeOperator */: - ts.Debug.type(node); - return ts.factory.updateTypeOperatorNode(node, visitTypeNode(node.type)); - case 190 /* IndexedAccessType */: - ts.Debug.type(node); - return ts.factory.updateIndexedAccessTypeNode(node, visitTypeNode(node.objectType), visitTypeNode(node.indexType)); - case 191 /* MappedType */: - ts.Debug.type(node); - return ts.factory.updateMappedTypeNode(node, visit(node.readonlyToken, ts.isReadonlyKeywordOrPlusOrMinusToken), visitMappedTypeParameter(node.typeParameter), visitTypeNode(node.nameType), visit(node.questionToken, ts.isQuestionOrPlusOrMinusToken), visitTypeNode(node.type)); - case 192 /* LiteralType */: - ts.Debug.type(node); - return ts.factory.updateLiteralTypeNode(node, visitExpression(node.literal, ts.isLiteralTypeLikeExpression)); - case 194 /* TemplateLiteralType */: - ts.Debug.type(node); - return ts.factory.updateTemplateLiteralType(node, visit(node.head, ts.isTemplateHead), visitList(node.templateSpans, ts.isTemplateLiteralTypeSpan)); - case 195 /* TemplateLiteralTypeSpan */: - ts.Debug.type(node); - return ts.factory.updateTemplateLiteralTypeSpan(node, visitTypeNode(node.type), visit(node.literal, ts.isTemplateMiddleOrTemplateTail)); - // Binding patterns - case 197 /* ObjectBindingPattern */: - ts.Debug.type(node); - return ts.factory.updateObjectBindingPattern(node, visitList(node.elements, ts.isBindingElement)); - case 198 /* ArrayBindingPattern */: - ts.Debug.type(node); - return ts.factory.updateArrayBindingPattern(node, visitList(node.elements, ts.isArrayBindingElement)); - case 199 /* BindingElement */: - ts.Debug.type(node); - return ts.factory.updateBindingElement(node, visit(node.dotDotDotToken, ts.isDotDotDotToken), visitPropertyName(node.propertyName), visitBindingName(node.name), visitExpression(node.initializer)); - // Misc - case 229 /* TemplateSpan */: - ts.Debug.type(node); - return ts.factory.updateTemplateSpan(node, visitExpression(node.expression), visit(node.literal, ts.isTemplateMiddleOrTemplateTail)); - // Element - case 231 /* Block */: - ts.Debug.type(node); - return ts.factory.updateBlock(node, visitList(node.statements, ts.isStatement)); - case 233 /* VariableStatement */: - ts.Debug.type(node); - return ts.factory.updateVariableStatement(node, visitList(node.modifiers, ts.isModifier), visit(node.declarationList, ts.isVariableDeclarationList)); - case 234 /* ExpressionStatement */: - ts.Debug.type(node); - return ts.factory.updateExpressionStatement(node, visitExpression(node.expression)); - case 235 /* IfStatement */: - ts.Debug.type(node); - return ts.factory.updateIfStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.thenStatement), visitEmbeddedStatement(node.elseStatement)); - case 236 /* DoStatement */: - ts.Debug.type(node); - return ts.factory.updateDoStatement(node, visitEmbeddedStatement(node.statement), visitExpression(node.expression)); - case 237 /* WhileStatement */: - ts.Debug.type(node); - return ts.factory.updateWhileStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 238 /* ForStatement */: - ts.Debug.type(node); - return ts.factory.updateForStatement(node, visitForInitializer(node.initializer), visitExpression(node.condition), visitExpression(node.incrementor), visitEmbeddedStatement(node.statement)); - case 239 /* ForInStatement */: - ts.Debug.type(node); - return ts.factory.updateForInStatement(node, visitForInitializer(node.initializer), visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 240 /* ForOfStatement */: - ts.Debug.type(node); - return ts.factory.updateForOfStatement(node, visit(node.awaitModifier, ts.isAwaitKeyword), visitForInitializer(node.initializer), visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 241 /* ContinueStatement */: - ts.Debug.type(node); - return ts.factory.updateContinueStatement(node, visitIdentifierName(node.label)); - case 242 /* BreakStatement */: - ts.Debug.type(node); - return ts.factory.updateBreakStatement(node, visitIdentifierName(node.label)); - case 243 /* ReturnStatement */: - ts.Debug.type(node); - return ts.factory.updateReturnStatement(node, visitExpression(node.expression)); - case 244 /* WithStatement */: - ts.Debug.type(node); - return ts.factory.updateWithStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 245 /* SwitchStatement */: - ts.Debug.type(node); - return ts.factory.updateSwitchStatement(node, visitExpression(node.expression), visit(node.caseBlock, ts.isCaseBlock)); - case 246 /* LabeledStatement */: - ts.Debug.type(node); - return ts.factory.updateLabeledStatement(node, visitIdentifierName(node.label), visitEmbeddedStatement(node.statement)); - case 247 /* ThrowStatement */: - ts.Debug.type(node); - return ts.factory.updateThrowStatement(node, visitExpression(node.expression)); - case 248 /* TryStatement */: - ts.Debug.type(node); - return ts.factory.updateTryStatement(node, visit(node.tryBlock, ts.isBlock), visit(node.catchClause, ts.isCatchClause), visit(node.finallyBlock, ts.isBlock)); - // Declarations - case 250 /* VariableDeclaration */: - ts.Debug.type(node); - return ts.factory.updateVariableDeclaration(node, visitBindingName(node.name), visit(node.exclamationToken, ts.isExclamationToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 251 /* VariableDeclarationList */: - ts.Debug.type(node); - return ts.factory.updateVariableDeclarationList(node, visitList(node.declarations, ts.isVariableDeclaration)); - case 252 /* FunctionDeclaration */: - ts.Debug.type(node); - return ts.factory.updateFunctionDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 253 /* ClassDeclaration */: - ts.Debug.type(node); - return ts.factory.updateClassDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isClassElement)); - case 254 /* InterfaceDeclaration */: - ts.Debug.type(node); - return ts.factory.updateInterfaceDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isTypeElement)); - case 255 /* TypeAliasDeclaration */: - ts.Debug.type(node); - return ts.factory.updateTypeAliasDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitTypeNode(node.type)); - case 256 /* EnumDeclaration */: - ts.Debug.type(node); - return ts.factory.updateEnumDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.members, ts.isEnumMember)); - case 257 /* ModuleDeclaration */: - ts.Debug.type(node); - return ts.factory.updateModuleDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitModuleName(node.name), visit(node.body, ts.isModuleBody)); - case 258 /* ModuleBlock */: - ts.Debug.type(node); - return ts.factory.updateModuleBlock(node, visitList(node.statements, ts.isStatement)); - case 259 /* CaseBlock */: - ts.Debug.type(node); - return ts.factory.updateCaseBlock(node, visitList(node.clauses, ts.isCaseOrDefaultClause)); - case 260 /* NamespaceExportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateNamespaceExportDeclaration(node, visitIdentifierName(node.name)); - case 261 /* ImportEqualsDeclaration */: - ts.Debug.type(node); - return ts.factory.updateImportEqualsDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), node.isTypeOnly, visitIdentifierName(node.name), visit(node.moduleReference, ts.isModuleReference)); - case 262 /* ImportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateImportDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.importClause, ts.isImportClause), visitExpression(node.moduleSpecifier)); - case 263 /* ImportClause */: - ts.Debug.type(node); - return ts.factory.updateImportClause(node, node.isTypeOnly, visitIdentifierName(node.name), visit(node.namedBindings, ts.isNamedImportBindings)); - case 264 /* NamespaceImport */: - ts.Debug.type(node); - return ts.factory.updateNamespaceImport(node, visitIdentifierName(node.name)); - case 270 /* NamespaceExport */: - ts.Debug.type(node); - return ts.factory.updateNamespaceExport(node, visitIdentifierName(node.name)); - case 265 /* NamedImports */: - ts.Debug.type(node); - return ts.factory.updateNamedImports(node, visitList(node.elements, ts.isImportSpecifier)); - case 266 /* ImportSpecifier */: - ts.Debug.type(node); - return ts.factory.updateImportSpecifier(node, visitIdentifierName(node.propertyName), visitIdentifierName(node.name)); - case 267 /* ExportAssignment */: - ts.Debug.type(node); - return ts.factory.updateExportAssignment(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitExpression(node.expression)); - case 268 /* ExportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateExportDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), node.isTypeOnly, visit(node.exportClause, ts.isNamedExportBindings), visitExpression(node.moduleSpecifier)); - case 269 /* NamedExports */: - ts.Debug.type(node); - return ts.factory.updateNamedExports(node, visitList(node.elements, ts.isExportSpecifier)); - case 271 /* ExportSpecifier */: - ts.Debug.type(node); - return ts.factory.updateExportSpecifier(node, visitIdentifierName(node.propertyName), visitIdentifierName(node.name)); - case 272 /* MissingDeclaration */: - return node; - // Module references - case 273 /* ExternalModuleReference */: - ts.Debug.type(node); - return ts.factory.updateExternalModuleReference(node, visitExpression(node.expression)); - // JSX (non-expression) - case 276 /* JsxOpeningElement */: - ts.Debug.type(node); - return ts.factory.updateJsxOpeningElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression), visitList(node.typeArguments, ts.isTypeNode), visit(node.attributes, ts.isJsxAttributes)); - case 277 /* JsxClosingElement */: - ts.Debug.type(node); - return ts.factory.updateJsxClosingElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression)); - case 281 /* JsxAttribute */: - ts.Debug.type(node); - return ts.factory.updateJsxAttribute(node, visitIdentifierName(node.name), visitJsxAttributeValue(node.initializer)); - case 282 /* JsxAttributes */: - ts.Debug.type(node); - return ts.factory.updateJsxAttributes(node, visitList(node.properties, ts.isJsxAttributeLike)); - case 283 /* JsxSpreadAttribute */: - ts.Debug.type(node); - return ts.factory.updateJsxSpreadAttribute(node, visitExpression(node.expression)); - case 284 /* JsxExpression */: - ts.Debug.type(node); - return ts.factory.updateJsxExpression(node, visitExpression(node.expression)); - // Clauses - case 285 /* CaseClause */: - ts.Debug.type(node); - return ts.factory.updateCaseClause(node, visitExpression(node.expression), visitList(node.statements, ts.isStatement)); - case 286 /* DefaultClause */: - ts.Debug.type(node); - return ts.factory.updateDefaultClause(node, visitList(node.statements, ts.isStatement)); - case 287 /* HeritageClause */: - ts.Debug.type(node); - return ts.factory.updateHeritageClause(node, visitList(node.types, ts.isExpressionWithTypeArguments)); - case 288 /* CatchClause */: - ts.Debug.type(node); - return ts.factory.updateCatchClause(node, visit(node.variableDeclaration, ts.isVariableDeclaration), visit(node.block, ts.isBlock)); - // Property assignments - case 289 /* PropertyAssignment */: - ts.Debug.type(node); - return ts.factory.updatePropertyAssignment(node, visitPropertyName(node.name), visitExpression(node.initializer)); - case 290 /* ShorthandPropertyAssignment */: - ts.Debug.type(node); - return ts.factory.updateShorthandPropertyAssignment(node, visitIdentifierName(node.name, ts.isIdentifier), visitExpression(node.objectAssignmentInitializer)); - case 291 /* SpreadAssignment */: - ts.Debug.type(node); - return ts.factory.updateSpreadAssignment(node, visitExpression(node.expression)); - // Enum - case 292 /* EnumMember */: - ts.Debug.type(node); - return ts.factory.updateEnumMember(node, visitPropertyName(node.name), visitExpression(node.initializer)); - // JSDoc nodes (only used in codefixes currently) - case 302 /* JSDocTypeExpression */: - case 303 /* JSDocNameReference */: - case 304 /* JSDocAllType */: - case 305 /* JSDocUnknownType */: - case 306 /* JSDocNullableType */: - case 307 /* JSDocNonNullableType */: - case 308 /* JSDocOptionalType */: - case 309 /* JSDocFunctionType */: - case 310 /* JSDocVariadicType */: - case 311 /* JSDocNamepathType */: - case 312 /* JSDocComment */: - case 314 /* JSDocTypeLiteral */: - case 315 /* JSDocSignature */: - case 317 /* JSDocTag */: - case 318 /* JSDocAugmentsTag */: - case 319 /* JSDocImplementsTag */: - case 320 /* JSDocAuthorTag */: - case 321 /* JSDocDeprecatedTag */: - case 322 /* JSDocClassTag */: - case 323 /* JSDocPublicTag */: - case 324 /* JSDocPrivateTag */: - case 325 /* JSDocProtectedTag */: - case 326 /* JSDocReadonlyTag */: - case 328 /* JSDocCallbackTag */: - case 329 /* JSDocEnumTag */: - case 330 /* JSDocParameterTag */: - case 337 /* JSDocPropertyTag */: - case 331 /* JSDocReturnTag */: - case 332 /* JSDocThisTag */: - case 333 /* JSDocTypeTag */: - case 334 /* JSDocTemplateTag */: - case 335 /* JSDocTypedefTag */: - case 336 /* JSDocSeeTag */: - return node; - // Transformation nodes (ignored) - } - if (ts.isExpression(node)) { - // If this was an expression that was originally in an `Unspecified` hint, - // re-trigger substitution using the correct hint. - hint = 1 /* Expression */; - if (substituteNode !== ts.noEmitSubstitution) { - node = substituteNode(hint, node); - } - } - else if (ts.isSourceFile(node)) { - return preprintSourceFile(node); - } - } - if (hint === 1 /* Expression */) { - switch (node.kind) { - // Identifiers - case 78 /* Identifier */: - return preprintIdentifier(node); - // Expression - case 200 /* ArrayLiteralExpression */: - ts.Debug.type(node); - return ts.factory.updateArrayLiteralExpression(node, visitExpressionList(node.elements)); - case 201 /* ObjectLiteralExpression */: - ts.Debug.type(node); - return ts.factory.updateObjectLiteralExpression(node, visitList(node.properties, ts.isObjectLiteralElementLike)); - case 202 /* PropertyAccessExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updatePropertyAccessChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitMemberName(node.name)); - } - ts.Debug.type(node); - return ts.factory.updatePropertyAccessExpression(node, visitExpression(node.expression), visitMemberName(node.name)); - case 203 /* ElementAccessExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateElementAccessChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitExpression(node.argumentExpression)); - } - ts.Debug.type(node); - return ts.factory.updateElementAccessExpression(node, visitExpression(node.expression), visitExpression(node.argumentExpression)); - case 204 /* CallExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateCallChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - } - ts.Debug.type(node); - return ts.factory.updateCallExpression(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - case 205 /* NewExpression */: - ts.Debug.type(node); - return ts.factory.updateNewExpression(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - case 206 /* TaggedTemplateExpression */: - ts.Debug.type(node); - return ts.factory.updateTaggedTemplateExpression(node, visitExpression(node.tag), visitTypeNodeList(node.typeArguments), visitExpression(node.template, ts.isTemplateLiteral)); - case 207 /* TypeAssertionExpression */: - ts.Debug.type(node); - return ts.factory.updateTypeAssertion(node, visitTypeNode(node.type), visitExpression(node.expression)); - case 208 /* ParenthesizedExpression */: - ts.Debug.type(node); - return ts.factory.updateParenthesizedExpression(node, visitExpression(node.expression)); - case 209 /* FunctionExpression */: - ts.Debug.type(node); - return ts.factory.updateFunctionExpression(node, visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 210 /* ArrowFunction */: - ts.Debug.type(node); - return ts.factory.updateArrowFunction(node, visitList(node.modifiers, ts.isModifier), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visit(node.equalsGreaterThanToken, ts.isEqualsGreaterThanToken), visitConciseBody(node.body)); - case 211 /* DeleteExpression */: - ts.Debug.type(node); - return ts.factory.updateDeleteExpression(node, visitExpression(node.expression)); - case 212 /* TypeOfExpression */: - ts.Debug.type(node); - return ts.factory.updateTypeOfExpression(node, visitExpression(node.expression)); - case 213 /* VoidExpression */: - ts.Debug.type(node); - return ts.factory.updateVoidExpression(node, visitExpression(node.expression)); - case 214 /* AwaitExpression */: - ts.Debug.type(node); - return ts.factory.updateAwaitExpression(node, visitExpression(node.expression)); - case 215 /* PrefixUnaryExpression */: - ts.Debug.type(node); - return ts.factory.updatePrefixUnaryExpression(node, visitExpression(node.operand)); - case 216 /* PostfixUnaryExpression */: - ts.Debug.type(node); - return ts.factory.updatePostfixUnaryExpression(node, visitExpression(node.operand)); - case 217 /* BinaryExpression */: - return preprintBinaryExpression(node); - case 218 /* ConditionalExpression */: - ts.Debug.type(node); - return ts.factory.updateConditionalExpression(node, visitExpression(node.condition), visit(node.questionToken, ts.isQuestionToken), visitExpression(node.whenTrue), visit(node.colonToken, ts.isColonToken), visitExpression(node.whenFalse)); - case 219 /* TemplateExpression */: - ts.Debug.type(node); - return ts.factory.updateTemplateExpression(node, visit(node.head, ts.isTemplateHead), visitList(node.templateSpans, ts.isTemplateSpan)); - case 220 /* YieldExpression */: - ts.Debug.type(node); - return ts.factory.updateYieldExpression(node, visit(node.asteriskToken, ts.isAsteriskToken), visitExpression(node.expression)); - case 221 /* SpreadElement */: - ts.Debug.type(node); - return ts.factory.updateSpreadElement(node, visitExpression(node.expression)); - case 222 /* ClassExpression */: - ts.Debug.type(node); - return ts.factory.updateClassExpression(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isClassElement)); - case 225 /* AsExpression */: - ts.Debug.type(node); - return ts.factory.updateAsExpression(node, visitExpression(node.expression), visitTypeNode(node.type)); - case 226 /* NonNullExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateNonNullChain(node, visitExpression(node.expression)); - } - ts.Debug.type(node); - return ts.factory.updateNonNullExpression(node, visitExpression(node.expression)); - case 227 /* MetaProperty */: - ts.Debug.type(node); - return ts.factory.updateMetaProperty(node, visitIdentifierName(node.name)); - // JSX (expression only) - case 274 /* JsxElement */: - ts.Debug.type(node); - return ts.factory.updateJsxElement(node, visit(node.openingElement, ts.isJsxOpeningElement), visitList(node.children, ts.isJsxChild), visit(node.closingElement, ts.isJsxClosingElement)); - case 275 /* JsxSelfClosingElement */: - ts.Debug.type(node); - return ts.factory.updateJsxSelfClosingElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression), visitList(node.typeArguments, ts.isTypeNode), visit(node.attributes, ts.isJsxAttributes)); - case 278 /* JsxFragment */: - ts.Debug.type(node); - return ts.factory.updateJsxFragment(node, visit(node.openingFragment, ts.isJsxOpeningFragment), visitList(node.children, ts.isJsxChild), visit(node.closingFragment, ts.isJsxClosingFragment)); - // Transformation nodes - case 340 /* PartiallyEmittedExpression */: - ts.Debug.type(node); - return ts.factory.updatePartiallyEmittedExpression(node, visitExpression(node.expression)); - case 341 /* CommaListExpression */: - ts.Debug.type(node); - return ts.factory.updateCommaListExpression(node, visitExpressionList(node.elements, ts.isExpression)); - } - } - if (ts.Debug.shouldAssert(1 /* Normal */)) { - // Any other node should not have children or this list isn't up to date. - ts.Debug.assertMissingNode(ts.forEachChild(node, ts.identity), "Expected " + ts.Debug.formatSyntaxKind(node.kind) + " to contain no children."); - } - // No need to visit nodes with no children. - return node; - } - function preprintSourceFile(node) { - return ts.factory.updateSourceFile(node, visitList(node.statements, ts.isStatement)); - } - function preprintIdentifier(node) { - return ts.factory.updateIdentifier(node, visitList(node.typeArguments, ts.isTypeNodeOrTypeParameterDeclaration)); - } - function preprintTypeParameterDeclaration(node) { - return ts.factory.updateTypeParameterDeclaration(node, visitIdentifierName(node.name), visitTypeNode(node.constraint), visitTypeNode(node.default)); - } - function createPreprintBinaryExpression() { - return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); - function onEnter(node, state) { - if (state) { - state.stackIndex++; - state.leftStack[state.stackIndex] = node.left; - state.operatorStack[state.stackIndex] = node.operatorToken; - state.rightStack[state.stackIndex] = node.right; - } - else { - state = { - stackIndex: 0, - leftStack: [node.left], - operatorStack: [node.operatorToken], - rightStack: [node.right], - }; - } - return state; - } - function onLeft(left, state, _node) { - return maybeVisitExpression(left, state, "left"); - } - function onOperator(operator, state, _node) { - state.operatorStack[state.stackIndex] = visit(operator, ts.isBinaryOperatorToken); - } - function onRight(right, state, _node) { - return maybeVisitExpression(right, state, "right"); - } - function onExit(node, state) { - var left = state.leftStack[state.stackIndex]; - var operator = state.operatorStack[state.stackIndex]; - var right = state.rightStack[state.stackIndex]; - if (state.stackIndex > 0) { - state.stackIndex--; - } - return ts.factory.updateBinaryExpression(node, left, operator, right); - } - function foldState(state, result, side) { - (side === "left" ? state.leftStack : state.rightStack)[state.stackIndex] = result; - return state; - } - function maybeVisitExpression(node, state, side) { - // Get the first supported pipeline phase for this node. We can skip several stack - // frames if we aren't doing emit notification, so we check for substitution and - // direct callbacks and execute those immediately. - var pipelinePhase = getPipelinePhase(0 /* Notification */, node); - if (pipelinePhase === pipelineVisitWithSubstitution) { - // The next phase after substitution is always direct visitation, so we can reduce the call stack - // depth by proceding to the direct visitor. - node = ts.cast(substituteNode(1 /* Expression */, node), ts.isExpression); - pipelinePhase = pipelineVisitDirect; - } - if (pipelinePhase === pipelineVisitDirect && ts.isBinaryExpression(node)) { - // If we are visiting directly and the next node is a BinaryExpression, we can - // add it to the stack and continue the trampoline. - return node; - } - else { - // Visit the expression and store the result on whichever side we are currently visiting. - (side === "left" ? state.leftStack : state.rightStack)[state.stackIndex] = visitExpression(node, ts.isExpression); - } - } - } - var preprintBinaryExpression = createPreprintBinaryExpression(); - function preprint(hint, node) { - // If we're not performing substitution or notification, we have no work to do here. - if (substituteNode === ts.noEmitSubstitution && - onEmitNode === ts.noEmitNotification) { - return node; - } - switch (hint) { - case 0 /* SourceFile */: return visitSourceFile(ts.cast(node, ts.isSourceFile)); - case 1 /* Expression */: return visitExpression(ts.cast(node, ts.isExpression)); - case 2 /* IdentifierName */: return visitIdentifierName(ts.cast(node, ts.isIdentifier)); - case 3 /* MappedTypeParameter */: return visitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 5 /* EmbeddedStatement */: return visitEmbeddedStatement(ts.cast(node, ts.isStatement)); - case 6 /* JsxAttributeValue */: return visitJsxAttributeValue(ts.cast(node, ts.isStringLiteralOrJsxExpression)); - default: return visit(node); - } - } - return preprint; - } function createBracketsMap() { var brackets = []; brackets[1024 /* Braces */] = ["{", "}"]; @@ -109240,6 +109176,7 @@ var ts; var hasEmitBlockingDiagnostics = new ts.Map(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; + var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { @@ -109254,7 +109191,7 @@ var ts; }); }; } else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } @@ -109263,7 +109200,8 @@ var ts; actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { - var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; // TODO: GH#18217 actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -109420,6 +109358,7 @@ var ts; } }); } + typeReferenceDirectiveResolutionCache = undefined; // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; var program = { @@ -109613,13 +109552,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_15 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_14.push(resolvedModule); + result_15.push(resolvedModule); } - return result_14; + return result_15; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -111051,12 +110990,14 @@ var ts; return host.getCanonicalFileName(fileName); } function processImportedModules(file) { + var _a; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var resolutions = resolveModuleNamesReusingOldState(moduleNames, file); ts.Debug.assert(resolutions.length === moduleNames.length); + var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options; for (var index = 0; index < moduleNames.length; index++) { var resolution = resolutions[index]; ts.setResolvedModule(file, moduleNames[index], resolution); @@ -111079,11 +111020,11 @@ var ts; // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !ts.getAllowJSCompilerOption(options)) + && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile)) && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -112171,7 +112112,7 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos: fileInfos, @@ -112971,7 +112912,16 @@ var ts; var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - return signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; + var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); var referencedMap; if (state.referencedMap) { @@ -113020,7 +112970,7 @@ var ts; return { fileNames: fileNames, fileInfos: fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, @@ -113052,17 +113002,16 @@ var ts; return fileIdListId; } } - function convertToReusableCompilerOptions(options, relativeToBuildInfo) { - var result = {}; + function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { + var result; var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo); + 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.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { @@ -113378,6 +113327,14 @@ var ts; state.affectedFilesPendingEmitIndex = 0; } } + function toBuilderStateFileInfo(fileInfo) { + return ts.isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + ts.isString(fileInfo.signature) ? + fileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; + } + ts.toBuilderStateFileInfo = toBuilderStateFileInfo; function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { var _a; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); @@ -113385,10 +113342,10 @@ var ts; 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), fileInfo); }); + program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); var state = { fileInfos: fileInfos, - compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, referencedMap: toMapOfReferencedSet(program.referencedMap), exportedModulesMap: toMapOfReferencedSet(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]; }), @@ -113548,9 +113505,9 @@ var ts; var resolutionsWithFailedLookups = []; var resolvedFileToResolution = ts.createMultiMap(); var hasChangedAutomaticTypeDirectiveNames = false; - var failedLookupChecks = []; - var startsWithPathChecks = []; - var isInDirectoryChecks = []; + var failedLookupChecks; + var startsWithPathChecks; + var isInDirectoryChecks; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -113559,9 +113516,12 @@ var ts; var resolvedModuleNames = new ts.Map(); var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache); var resolvedTypeReferenceDirectives = new ts.Map(); var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -113619,9 +113579,9 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.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(); @@ -113657,9 +113617,8 @@ var ts; isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -113686,7 +113645,7 @@ 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), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; @@ -113697,6 +113656,9 @@ var ts; // Default return the result from the first pass return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } function resolveNamesWithLocalCache(_a) { var _b; var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; @@ -113784,7 +113746,7 @@ var ts; redirectedReference: redirectedReference, cache: resolvedTypeReferenceDirectives, perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, - loader: ts.resolveTypeReferenceDirective, + loader: resolveTypeReferenceDirective, getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, }); @@ -114059,7 +114021,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -114077,8 +114039,8 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -114089,27 +114051,33 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(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. + var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { return resolution.failedLookupLocations.some(function (location) { var locationPath = resolutionHost.toPath(location); return ts.contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) || - isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, 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); })); }); } function closeTypeRootsWatch() { @@ -114330,7 +114298,7 @@ var ts; if (!baseUrl && !paths || relativePreference === 0 /* Relative */) { return relativePath; } - var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl; + var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -114345,7 +114313,9 @@ var ts; return nonRelative; } if (relativePreference === 3 /* ExternalNonRelative */) { - var projectDirectory = host.getCurrentDirectory(); + var projectDirectory = compilerOptions.configFilePath ? + ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName); var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory); var targetIsInternal = ts.startsWith(modulePath, projectDirectory); @@ -114420,9 +114390,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 links = host.getSymlinkCache ? host.getSymlinkCache() @@ -114445,10 +114415,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; } }); }); @@ -114579,7 +114549,7 @@ var ts; ts.startsWith(relativeToBaseUrl, prefix) && ts.endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } @@ -116180,12 +116150,19 @@ var ts; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); 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) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } + if (!compilerHost.resolveTypeReferenceDirectives) { + var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4); + }; + } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -116210,6 +116187,7 @@ var ts; projectErrorsReported: new ts.Map(), compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, + typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, // Mutable state buildOrder: undefined, readFileWithCache: function (f) { return host.readFile(f); }, @@ -116397,7 +116375,7 @@ var ts; function disableCache(state) { if (!state.cache) return; - var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache; + var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -116406,10 +116384,8 @@ var ts; compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear(); state.cache = undefined; } function clearProjectStatus(state, resolved) { @@ -116576,6 +116552,7 @@ var ts; return withProgramOrUndefined(action) || ts.emptyArray; } function createProgram() { + var _a, _b; ts.Debug.assert(program === undefined); if (state.options.dry) { reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -116595,7 +116572,8 @@ var ts; var host = state.host, compilerHost = state.compilerHost; state.projectCompilerOptions = config.options; // Update module resolution cache if needed - updateModuleResolutionCache(state, project, config); + (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { @@ -116770,7 +116748,7 @@ var ts; emitBundle(writeFile, customTransformers); break; case BuildStep.BuildInvalidatedProjectOfBundle: - ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; case BuildStep.QueueReferencingProjects: @@ -116912,31 +116890,6 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache(state, proj, config) { - if (!state.moduleResolutionCache) - return; - // Update module resolution cache if needed - var moduleResolutionCache = state.moduleResolutionCache; - var projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - // The own map will be for projectCompilerOptions - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - // Set correct own map - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - var ref = { - sourceFile: config.options.configFile, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time var tsconfigTime = ts.getModifiedTime(state.host, configFile); @@ -116949,6 +116902,7 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { + var force = !!state.options.force; var newestInputFileName = undefined; var newestInputFileTime = minimumDate; var host = state.host; @@ -116961,11 +116915,13 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = ts.getModifiedTime(host, inputFile); - host.getModifiedTime(inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + var inputTime = ts.getModifiedTime(host, inputFile); + host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } // Container if no files are specified in the project @@ -116984,36 +116940,38 @@ var ts; var missingOutputFileName; var newestDeclarationFileContentChangedTime = minimumDate; var isOutOfDateWithInputs = false; - 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 (isDeclarationFile(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + 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 (isDeclarationFile(output)) { + var outputModifiedTime = ts.getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } var pseudoUpToDate = false; @@ -117049,7 +117007,8 @@ var ts; }; } // Check oldest output file name only if there is no missing output file name - if (!missingOutputFileName) { + // (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) { @@ -117095,7 +117054,7 @@ var ts; if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -117237,7 +117196,7 @@ var ts; } } } - function build(state, project, cancellationToken, onlyReferences) { + function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -117249,7 +117208,7 @@ var ts; if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -117431,9 +117390,9 @@ var ts; function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: function (project, cancellationToken) { return build(state, project, cancellationToken); }, + build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); }, clean: function (project) { return clean(state, project); }, - buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); }, + buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, /*onlyReferences*/ true); }, cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); }, getNextInvalidatedProject: function (cancellationToken) { setupInitialBuild(state, cancellationToken); @@ -117523,6 +117482,9 @@ 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)); @@ -118287,7 +118249,7 @@ var ts; case 167 /* Constructor */: return "constructor" /* constructorImplementationElement */; case 160 /* TypeParameter */: return "type parameter" /* typeParameterElement */; case 292 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 161 /* Parameter */: return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 161 /* Parameter */: return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; case 261 /* ImportEqualsDeclaration */: case 266 /* ImportSpecifier */: case 271 /* ExportSpecifier */: @@ -118971,6 +118933,21 @@ var ts; return current; } } + /** + * Returns the first token where position is in [start, end), + * excluding `JsxText` tokens containing only whitespace. + */ + function findFirstNonJsxWhitespaceToken(sourceFile, position) { + var tokenAtPosition = getTokenAtPosition(sourceFile, position); + while (isWhiteSpaceOnlyJsxText(tokenAtPosition)) { + var nextToken = findNextToken(tokenAtPosition, tokenAtPosition.parent, sourceFile); + if (!nextToken) + return; + tokenAtPosition = nextToken; + } + return tokenAtPosition; + } + ts.findFirstNonJsxWhitespaceToken = findFirstNonJsxWhitespaceToken; /** * The token on the left of the position is the token that strictly includes the position * or sits to the left of the cursor if it is on a boundary. For example @@ -119965,6 +119942,14 @@ var ts; return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); } ts.operatorPart = operatorPart; + function parameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.parameterName); + } + ts.parameterNamePart = parameterNamePart; + function propertyNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.propertyName); + } + ts.propertyNamePart = propertyNamePart; function textOrKeywordPart(text) { var kind = ts.stringToToken(text); return kind === undefined @@ -119976,6 +119961,14 @@ var ts; return displayPart(text, ts.SymbolDisplayPartKind.text); } ts.textPart = textPart; + function typeAliasNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.aliasName); + } + ts.typeAliasNamePart = typeAliasNamePart; + function typeParameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.typeParameterName); + } + ts.typeParameterNamePart = typeParameterNamePart; function linkTextPart(text) { return displayPart(text, ts.SymbolDisplayPartKind.linkText); } @@ -119996,6 +119989,7 @@ var ts; } ts.linkPart = linkPart; function buildLinkParts(link, checker) { + var _a; var parts = [linkPart("{@link ")]; if (!link.name) { if (link.text) { @@ -120004,8 +119998,9 @@ var ts; } else { var symbol = checker === null || checker === void 0 ? void 0 : checker.getSymbolAtLocation(link.name); - if (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) { - parts.push(linkNamePart(link.name, symbol.valueDeclaration)); + var decl = (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) || ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]); + if (decl) { + parts.push(linkNamePart(link.name, decl)); if (link.text) { parts.push(linkTextPart(link.text)); } @@ -123285,6 +123280,7 @@ var ts; sourceDisplay: sourceDisplay, isSnippet: isSnippet, isPackageJsonImport: originIsPackageJsonImport(origin) || undefined, + isImportStatementCompletion: originIsResolvedExport(origin) || undefined, data: data, }; } @@ -124086,7 +124082,8 @@ var ts; return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined; } function tryGetGlobalSymbols() { - var result = tryGetObjectLikeCompletionSymbols() + var result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() + || tryGetObjectLikeCompletionSymbols() || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() @@ -124231,8 +124228,9 @@ var ts; } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 111 /* TypeOfKeyword */ && - (contextToken.parent.kind === 177 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + ((contextToken.kind === 111 /* TypeOfKeyword */ && + (contextToken.parent.kind === 177 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent))) || + (contextToken.kind === 127 /* AssertsKeyword */ && contextToken.parent.kind === 173 /* TypePredicate */)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { @@ -124449,6 +124447,25 @@ var ts; return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) || position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken))); } + function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() { + var typeLiteralNode = tryGetTypeLiteralNode(contextToken); + if (!typeLiteralNode) + return 0 /* Continue */; + var intersectionTypeNode = ts.isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : undefined; + var containerTypeNode = intersectionTypeNode || typeLiteralNode; + var containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker); + if (!containerExpectedType) + return 0 /* Continue */; + var containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode); + var members = getPropertiesForCompletion(containerExpectedType, typeChecker); + var existingMembers = getPropertiesForCompletion(containerActualType, typeChecker); + var existingMemberEscapedNames = new ts.Set(); + existingMembers.forEach(function (s) { return existingMemberEscapedNames.add(s.escapedName); }); + symbols = ts.filter(members, function (s) { return !existingMemberEscapedNames.has(s.escapedName); }); + completionKind = 0 /* ObjectPropertyDeclaration */; + isNewIdentifierLocation = true; + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in object literals and object binding patterns. * Relevant symbols are stored in the captured 'symbols' variable. @@ -124833,7 +124850,7 @@ var ts; case 41 /* AsteriskToken */: return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } - // If the previous token is keyword correspoding to class member completion keyword + // If the previous token is keyword corresponding to class member completion keyword // there will be completion available here if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; @@ -124868,6 +124885,31 @@ var ts; case 129 /* AsyncKeyword */: return ts.isPropertyDeclaration(contextToken.parent); } + // If we are inside a class declaration, and `constructor` is totally not present, + // but we request a completion manually at a whitespace... + var ancestorClassLike = ts.findAncestor(contextToken.parent, ts.isClassLike); + if (ancestorClassLike && contextToken === previousToken && isPreviousPropertyDeclarationTerminated(contextToken, position)) { + return false; // Don't block completions. + } + var ancestorPropertyDeclaraion = ts.getAncestor(contextToken.parent, 164 /* PropertyDeclaration */); + // If we are inside a class declaration and typing `constructor` after property declaration... + if (ancestorPropertyDeclaraion + && contextToken !== previousToken + && ts.isClassLike(previousToken.parent.parent) + // And the cursor is at the token... + && position <= previousToken.end) { + // If we are sure that the previous property declaration is terminated according to newline or semicolon... + if (isPreviousPropertyDeclarationTerminated(contextToken, previousToken.end)) { + return false; // Don't block completions. + } + else if (contextToken.kind !== 62 /* EqualsToken */ + // Should not block: `class C { blah = c/**/ }` + // But should block: `class C { blah = somewhat c/**/ }` and `class C { blah: SomeType c/**/ }` + && (ts.isInitializedProperty(ancestorPropertyDeclaraion) + || ts.hasType(ancestorPropertyDeclaraion))) { + return true; + } + } return ts.isDeclarationName(contextToken) && !ts.isShorthandPropertyAssignment(contextToken.parent) && !ts.isJsxAttribute(contextToken.parent) @@ -124875,6 +124917,11 @@ var ts; // If `contextToken !== previousToken`, this is `class C ex/**/`. && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } + function isPreviousPropertyDeclarationTerminated(contextToken, position) { + return contextToken.kind !== 62 /* EqualsToken */ && + (contextToken.kind === 26 /* SemicolonToken */ + || !ts.positionsAreOnSameLine(contextToken.end, position, sourceFile)); + } function isFunctionLikeButNotConstructor(kind) { return ts.isFunctionLikeKind(kind) && kind !== 167 /* Constructor */; } @@ -125280,6 +125327,12 @@ var ts; } if (!contextToken) return undefined; + // class C { blah; constructor/**/ } and so on + if (location.kind === 132 /* ConstructorKeyword */ + // class C { blah \n constructor/**/ } + || (ts.isIdentifier(contextToken) && ts.isPropertyDeclaration(contextToken.parent) && ts.isClassLike(location))) { + return ts.findAncestor(contextToken, ts.isClassLike); + } switch (contextToken.kind) { case 62 /* EqualsToken */: return undefined; @@ -125305,6 +125358,44 @@ var ts; ? contextToken.parent.parent : undefined; } } + function tryGetTypeLiteralNode(node) { + if (!node) + return undefined; + var parent = node.parent; + switch (node.kind) { + case 18 /* OpenBraceToken */: + if (ts.isTypeLiteralNode(parent)) { + return parent; + } + break; + case 26 /* SemicolonToken */: + case 27 /* CommaToken */: + case 78 /* Identifier */: + if (parent.kind === 163 /* PropertySignature */ && ts.isTypeLiteralNode(parent.parent)) { + return parent.parent; + } + break; + } + return undefined; + } + function getConstraintOfTypeArgumentProperty(node, checker) { + if (!node) + return undefined; + if (ts.isTypeNode(node) && ts.isTypeReferenceType(node.parent)) { + return checker.getTypeArgumentConstraint(node); + } + var t = getConstraintOfTypeArgumentProperty(node.parent, checker); + if (!t) + return undefined; + switch (node.kind) { + case 163 /* PropertySignature */: + return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); + case 184 /* IntersectionType */: + case 178 /* TypeLiteral */: + case 183 /* UnionType */: + return t; + } + } // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes function isFromObjectTypeDeclaration(node) { return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); @@ -125364,7 +125455,8 @@ var ts; if (type) { return type; } - if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { + if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ && node === node.parent.left) { + // Object literal is assignment pattern: ({ | } = x) return typeChecker.getTypeAtLocation(node.parent); } return undefined; @@ -125865,6 +125957,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function isDocumentRegistryEntry(entry) { + return !!entry.sourceFile; + } function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); } @@ -125881,10 +125976,16 @@ var ts; var entries = buckets.get(name); var sourceFiles = []; entries.forEach(function (entry, name) { - sourceFiles.push({ - name: name, - refCount: entry.languageServiceRefCount - }); + if (isDocumentRegistryEntry(entry)) { + sourceFiles.push({ + name: name, + scriptKind: entry.sourceFile.scriptKind, + refCount: entry.languageServiceRefCount + }); + } + else { + entry.forEach(function (value, scriptKind) { return sourceFiles.push({ name: name, scriptKind: scriptKind, refCount: value.languageServiceRefCount }); }); + } }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); return { @@ -125910,10 +126011,17 @@ var ts; function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } + 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:" + scriptKind + " and sourceFile.scriptKind: " + (entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind) + ", !entry: " + !entry); + return entry; + } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); - var entry = bucket.get(path); + scriptKind = ts.ensureScriptKind(fileName, scriptKind); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; + var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -125922,7 +126030,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 0 }; - bucket.set(path, entry); + setBucketEntry(); } } if (!entry) { @@ -125935,7 +126043,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 1, }; - bucket.set(path, entry); + setBucketEntry(); } else { // We have an entry for this file. However, it may be for a different version of @@ -125958,25 +126066,49 @@ var ts; } ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; + function setBucketEntry() { + if (!bucketEntry) { + bucket.set(path, entry); + } + else if (isDocumentRegistryEntry(bucketEntry)) { + var scriptKindMap = new ts.Map(); + scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry); + scriptKindMap.set(scriptKind, entry); + bucket.set(path, scriptKindMap); + } + else { + bucketEntry.set(scriptKind, entry); + } + } } - function releaseDocument(fileName, compilationSettings) { + function releaseDocument(fileName, compilationSettings, scriptKind) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); + return releaseDocumentWithKey(path, key, scriptKind); } - function releaseDocumentWithKey(path, key) { + function releaseDocumentWithKey(path, key, scriptKind) { var bucket = ts.Debug.checkDefined(buckets.get(key)); - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.delete(path); + if (isDocumentRegistryEntry(bucketEntry)) { + bucket.delete(path); + } + else { + bucketEntry.delete(scriptKind); + if (bucketEntry.size === 1) { + bucket.set(path, ts.firstDefinedIterator(bucketEntry.values(), ts.identity)); + } + } } } - function getLanguageServiceRefCounts(path) { + function getLanguageServiceRefCounts(path, scriptKind) { return ts.arrayFrom(buckets.entries(), function (_a) { var key = _a[0], bucket = _a[1]; - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); return [key, entry && entry.languageServiceRefCount]; }); } @@ -126406,13 +126538,13 @@ var ts; function getExport() { var _a; var parent = node.parent; - var grandParent = parent.parent; + var grandparent = parent.parent; if (symbol.exportSymbol) { if (parent.kind === 202 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandParent) - ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandparent) + ? getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ false) : undefined; } else { @@ -126442,15 +126574,15 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(grandParent)) { - return getExportAssignmentExport(grandParent); + else if (ts.isExportAssignment(grandparent)) { + return getExportAssignmentExport(grandparent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(grandParent)) { - return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandparent)) { + return getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ true); } else if (ts.isJSDocTypedefTag(parent)) { return exportInfo(symbol, 0 /* Named */); @@ -126458,9 +126590,10 @@ var ts; } function getExportAssignmentExport(ex) { // Get the symbol for the `export =` node; its parent is the module it's the export of. - var exportingModuleSymbol = ts.Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + if (!ex.symbol.parent) + return undefined; var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; - return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: ex.symbol.parent, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; @@ -127412,9 +127545,9 @@ var ts; // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); } - else if (node && node.kind === 87 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */) { + else if (node && node.kind === 87 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) { addReference(node, symbol, state); - searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); @@ -127629,7 +127762,9 @@ var ts; for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { var node = _d[_c]; // Import specifiers should be handled by importSearches - if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + var symbol = checker.getSymbolAtLocation(node); + var hasExportAssignmentDeclaration = ts.some(symbol === null || symbol === void 0 ? void 0 : symbol.declarations, function (d) { return ts.tryCast(d, ts.isExportAssignment) ? true : false; }); + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) { cb(node); } } @@ -127936,6 +128071,10 @@ var ts; default: ts.Debug.assertNever(state.specialSearchKind); } + // Use the parent symbol if the location is commonjs require syntax on javascript files only. + referenceSymbol = ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 199 /* BindingElement */ && ts.isRequireVariableDeclaration(referenceLocation.parent) + ? referenceLocation.parent.symbol + : referenceSymbol; getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { @@ -128303,6 +128442,8 @@ var ts; case 166 /* MethodDeclaration */: case 165 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { + staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning object literals break; } // falls through @@ -128343,7 +128484,8 @@ var ts; return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; case 222 /* ClassExpression */: case 253 /* ClassDeclaration */: - // Make sure the container belongs to the same class + case 201 /* ObjectLiteralExpression */: + // Make sure the container belongs to the same class/object literals // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getSyntacticModifierFlags(container) & 32 /* Static */) === staticFlag; case 298 /* SourceFile */: @@ -129471,7 +129613,7 @@ var ts; end: node.getEnd(), fileName: node.text }, - unverified: !!verifiedFileName, + unverified: !verifiedFileName, }; } } @@ -129624,7 +129766,38 @@ var ts; var sourceFile = name.getSourceFile(); var textSpan = ts.createTextSpanFromNode(name, sourceFile); return __assign(__assign({ fileName: sourceFile.fileName, textSpan: textSpan, kind: symbolKind, name: symbolName, containerKind: undefined, // TODO: GH#18217 - containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !checker.isDeclarationVisible(declaration) }); + containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !isDefinitionVisible(checker, declaration) }); + } + function isDefinitionVisible(checker, declaration) { + if (checker.isDeclarationVisible(declaration)) + return true; + if (!declaration.parent) + return false; + // Variable initializers are visible if variable is visible + if (ts.hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) + return isDefinitionVisible(checker, declaration.parent); + // Handle some exceptions here like arrow function, members of class and object literal expression which are technically not visible but we want the definition to be determined by its parent + switch (declaration.kind) { + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + // Private/protected properties/methods are not visible + if (ts.hasEffectiveModifier(declaration, 8 /* Private */)) + return false; + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 167 /* Constructor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + return isDefinitionVisible(checker, declaration.parent); + default: + return false; + } } function createDefinitionFromSignatureDeclaration(typeChecker, decl) { return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); @@ -129717,6 +129890,7 @@ var ts; "kind", "lends", "license", + "link", "listens", "member", "memberof", @@ -129810,8 +129984,9 @@ var ts; return ts.flatMap(comment, function (node) { return node.kind === 313 /* JSDocText */ ? [ts.textPart(node.text)] : ts.buildLinkParts(node, checker); }); } function getCommentDisplayParts(tag, checker) { - var comment = tag.comment; - switch (tag.kind) { + var comment = tag.comment, kind = tag.kind; + var namePart = getTagNameDisplayPart(kind); + switch (kind) { case 319 /* JSDocImplementsTag */: return withNode(tag.class); case 318 /* JSDocAugmentsTag */: @@ -129826,7 +130001,9 @@ var ts; case 330 /* JSDocParameterTag */: case 336 /* JSDocSeeTag */: var name = tag.name; - return name ? withNode(name) : comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); + return name ? withNode(name) + : comment === undefined ? undefined + : getDisplayPartsFromComment(comment, checker); default: return comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); } @@ -129834,7 +130011,32 @@ var ts; return addComment(node.getText()); } function addComment(s) { - return comment ? __spreadArray([ts.textPart(s), ts.spacePart()], getDisplayPartsFromComment(comment, checker)) : [ts.textPart(s)]; + if (comment) { + if (s.match(/^https?$/)) { + return __spreadArray([ts.textPart(s)], getDisplayPartsFromComment(comment, checker)); + } + else { + return __spreadArray([namePart(s), ts.spacePart()], getDisplayPartsFromComment(comment, checker)); + } + } + else { + return [ts.textPart(s)]; + } + } + } + function getTagNameDisplayPart(kind) { + switch (kind) { + case 330 /* JSDocParameterTag */: + return ts.parameterNamePart; + case 337 /* JSDocPropertyTag */: + return ts.propertyNamePart; + case 334 /* JSDocTemplateTag */: + return ts.typeParameterNamePart; + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + return ts.typeAliasNamePart; + default: + return ts.textPart; } } function getJSDocTagNameCompletions() { @@ -131087,9 +131289,9 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences) { + function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); @@ -131124,26 +131326,35 @@ var ts; ? coalesce(importGroup) : importGroup; }); - // Delete or replace the first import. + // Delete all nodes if there are no imports. if (newImportDecls.length === 0) { - changeTracker.delete(sourceFile, oldImportDecls[0]); + // Consider the first node to have trailingTrivia as we want to exclude the + // "header" comment. + changeTracker.deleteNodes(sourceFile, oldImportDecls, { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, /*hasTrailingComment*/ true); } else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + var replaceOptions = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - // Delete any subsequent imports. - for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + }; + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions); + var hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions); + changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, hasTrailingComment); } } } OrganizeImports.organizeImports = organizeImports; - function removeUnusedImports(oldImports, sourceFile, program) { + function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { + // As a precaution, consider unused import detection to be destructive (GH #43051) + if (skipDestructiveCodeActions) { + return oldImports; + } var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); var jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile); @@ -132621,7 +132832,7 @@ var ts; function getRenameInfo(program, sourceFile, position, options) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); if (renameInfo) { return renameInfo; } @@ -132629,7 +132840,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -132649,7 +132860,7 @@ var ts; if (!declarations || declarations.length === 0) return; // Disallow rename for elements that are defined in the standard TypeScript library. - if (declarations.some(isDefinedInLibraryFile)) { + if (declarations.some(function (declaration) { return isDefinedInLibraryFile(program, declaration); })) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; @@ -132667,6 +132878,10 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), node, sourceFile); } + function isDefinedInLibraryFile(program, declaration) { + var sourceFile = declaration.getSourceFile(); + return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); @@ -133817,7 +134032,7 @@ var ts; diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } } - if (ts.isFunctionLikeDeclaration(node)) { + if (canBeConvertedToAsync(node)) { addConvertToAsyncFunctionDiagnostics(node, checker, diags); } node.forEachChild(check); @@ -133874,11 +134089,11 @@ var ts; returnsPromise(node, checker); } function returnsPromise(node, checker) { - var functionType = checker.getTypeAtLocation(node); - var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); - var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + var signature = checker.getSignatureFromDeclaration(node); + var returnType = signature ? checker.getReturnTypeOfSignature(signature) : undefined; return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } + ts.returnsPromise = returnsPromise; function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } @@ -133960,6 +134175,18 @@ var ts; } return false; } + function canBeConvertedToAsync(node) { + switch (node.kind) { + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + return true; + default: + return false; + } + } + ts.canBeConvertedToAsync = canBeConvertedToAsync; })(ts || (ts = {})); /* @internal */ var ts; @@ -134131,7 +134358,7 @@ var ts; symbolKind = "property" /* memberVariableElement */; } var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (location.parent && location.parent.kind === 202 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing @@ -137755,7 +137982,9 @@ var ts; function getAdjustedRange(sourceFile, startNode, endNode, options) { return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - function getAdjustedStartPosition(sourceFile, node, options) { + function getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment) { + var _a, _b; + if (hasTrailingComment === void 0) { hasTrailingComment = false; } var leadingTriviaOption = options.leadingTriviaOption; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); @@ -137786,6 +138015,15 @@ var ts; // when b is deleted - we delete it return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start; } + // if node has a trailing comments, use comment end position as the text has already been included. + if (hasTrailingComment) { + // Check first for leading comments as if the node is the first import, we want to exclude the trivia; + // otherwise we get the trailing comments. + var comment = ((_a = ts.getLeadingCommentRanges(sourceFile.text, fullStart)) === null || _a === void 0 ? void 0 : _a[0]) || ((_b = ts.getTrailingCommentRanges(sourceFile.text, fullStart)) === null || _b === void 0 ? void 0 : _b[0]); + if (comment) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } // get start position of the line following the line that contains fullstart position // (but only if the fullstart isn't the very beginning of the file) var nextLineStart = fullStart > 0 ? 1 : 0; @@ -137794,6 +138032,35 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } + /** Return the end position of a multiline comment of it is on another line; otherwise returns `undefined`; */ + function getEndPositionOfMultilineTrailingComment(sourceFile, node, options) { + var end = node.end; + var trailingTriviaOption = options.trailingTriviaOption; + if (trailingTriviaOption === TrailingTriviaOption.Include) { + // If the trailing comment is a multiline comment that extends to the next lines, + // return the end of the comment and track it for the next nodes to adjust. + var comments = ts.getTrailingCommentRanges(sourceFile.text, end); + if (comments) { + var nodeEndLine = ts.getLineOfLocalPosition(sourceFile, node.end); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + // Single line can break the loop as trivia will only be this line. + // Comments on subsequest lines are also ignored. + if (comment.kind === 2 /* SingleLineCommentTrivia */ || ts.getLineOfLocalPosition(sourceFile, comment.pos) > nodeEndLine) { + break; + } + // Get the end line of the comment and compare against the end line of the node. + // If the comment end line position and the multiline comment extends to multiple lines, + // then is safe to return the end position. + var commentEndLine = ts.getLineOfLocalPosition(sourceFile, comment.end); + if (commentEndLine > nodeEndLine) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } + } + } + return undefined; + } function getAdjustedEndPosition(sourceFile, node, options) { var _a; var end = node.end; @@ -137809,6 +138076,10 @@ var ts; } return end; } + var multilineEndPosition = getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + if (multilineEndPosition) { + return multilineEndPosition; + } var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd @@ -137820,13 +138091,6 @@ var ts; function isSeparator(node, candidate) { return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 201 /* ObjectLiteralExpression */)); } - function spaces(count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += " "; - } - return s; - } function isThisTypeAnnotatable(containingFunction) { return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction); } @@ -137871,6 +138135,17 @@ var ts; if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); }; + ChangeTracker.prototype.deleteNodes = function (sourceFile, nodes, options, hasTrailingComment) { + if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } + // When deleting multiple nodes we need to track if the end position is including multiline trailing comments. + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment); + var end = getAdjustedEndPosition(sourceFile, node, options); + this.deleteRange(sourceFile, { pos: pos, end: end }); + hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + } + }; ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; @@ -137913,6 +138188,10 @@ var ts; if (options === void 0) { options = useNonAdjustedPositions; } this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; + ChangeTracker.prototype.nodeHasTrailingComment = function (sourceFile, oldNode, configurableEnd) { + if (configurableEnd === void 0) { configurableEnd = useNonAdjustedPositions; } + return !!getEndPositionOfMultilineTrailingComment(sourceFile, oldNode, configurableEnd); + }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { var next = ts.findNextToken(node, node.parent, sourceFile); return next && next.kind === 27 /* CommaToken */ ? next : undefined; @@ -138256,47 +138535,22 @@ var ts; // a, b, c // create change for adding 'e' after 'a' as // - find start of next element after a (it is b) - // - use this start as start and end position in final change - // - build text of change by formatting the text of node + separator + whitespace trivia of b + // - use next element start as start and end position in final change + // - build text of change by formatting the text of node + whitespace trivia of b // in multiline case it will work as // a, // b, // c, // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') - // a,* - // ***insertedtext# + // a, + // insertedtext# // ###b, // c, - // find line and character of the next element - var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); - // find line and character of the token that precedes next element (usually it is separator) - var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); - var prefix = void 0; - var startPos = void 0; - if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { - // next element is located on the same line with separator: - // a,$$$$b - // ^ ^ - // | |-next element - // |-separator - // where $$$ is some leading trivia - // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces - // a, x,$$$$b - // ^ ^ ^ - // | | |-next element - // | |-new inserted node padded with spaces - // |-separator - startPos = nextToken.end; - prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); - } - else { - // next element is located on different line that separator - // let insert position be the beginning of the line that contains next element - startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); - } + var nextNode = containingList[index + 1]; + var startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart()); // write separator and leading trivia of the next element as suffix - var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, startPos); + this.insertNodesAt(sourceFile, startPos, [newNode], { suffix: suffix }); } } else { @@ -138827,7 +139081,9 @@ var ts; case 261 /* ImportEqualsDeclaration */: var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); // For first import, leave header comment in place, otherwise only delete JSDoc comments - deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + deleteNode(changes, sourceFile, node, { + leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine, + }); break; case 199 /* BindingElement */: var pattern = node.parent; @@ -139253,7 +139509,7 @@ var ts; ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code, - ts.Diagnostics.This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, ts.Diagnostics.Type_0_is_not_an_array_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators.code, @@ -140144,7 +140400,7 @@ var ts; functionToConvert = tokenAtPosition.parent.initializer; } else { - functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.canBeConvertedToAsync); } if (!functionToConvert) { return; @@ -140153,6 +140409,9 @@ var ts; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); + if (!ts.returnsPromise(functionToConvertRenamed, checker)) { + return; + } var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray; var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { @@ -141770,6 +142029,10 @@ var ts; if (!importClause || !ts.isStringLiteralLike(declaration.moduleSpecifier)) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; + // A type-only import may not have both a default and named imports, so the only way a name can + // be added to an existing type-only import is adding a named import to existing named bindings. + if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) + return undefined; return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 265 /* NamedImports */) ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.text, canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; @@ -142303,7 +142566,8 @@ var ts; ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, - ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code ]; var errorCodeFixIdMap = (_a = {}, _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code] = [ @@ -142312,6 +142576,9 @@ var ts; _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code] = [ ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers ], + _a[ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, + ], _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code] = [ ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers ], @@ -142350,6 +142617,7 @@ var ts; switch (errorCode) { case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: @@ -142359,16 +142627,23 @@ var ts; } } function doAddOverrideModifierChange(changeTracker, sourceFile, pos) { - var classElement = findContainerClassElement(sourceFile, pos); - changeTracker.insertModifierBefore(sourceFile, 156 /* OverrideKeyword */, classElement); + var classElement = findContainerClassElementLike(sourceFile, pos); + var modifiers = classElement.modifiers || ts.emptyArray; + var staticModifier = ts.find(modifiers, ts.isStaticModifier); + var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var modifierPos = staticModifier ? staticModifier.end : + accessibilityModifier ? accessibilityModifier.end : + classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + var options = accessibilityModifier || staticModifier ? { prefix: " " } : { suffix: " " }; + changeTracker.insertModifierAt(sourceFile, modifierPos, 156 /* OverrideKeyword */, options); } function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { - var classElement = findContainerClassElement(sourceFile, pos); + var classElement = findContainerClassElementLike(sourceFile, pos); var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 156 /* OverrideKeyword */; }); ts.Debug.assertIsDefined(overrideModifier); changeTracker.deleteModifier(sourceFile, overrideModifier); } - function isClassElementHasJSDoc(node) { + function isClassElementLikeHasJSDoc(node) { switch (node.kind) { case 167 /* Constructor */: case 164 /* PropertyDeclaration */: @@ -142376,18 +142651,20 @@ var ts; case 168 /* GetAccessor */: case 169 /* SetAccessor */: return true; + case 161 /* Parameter */: + return ts.isParameterPropertyDeclaration(node, node.parent); default: return false; } } - function findContainerClassElement(sourceFile, pos) { + function findContainerClassElementLike(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); var classElement = ts.findAncestor(token, function (node) { if (ts.isClassLike(node)) return "quit"; - return isClassElementHasJSDoc(node); + return isClassElementLikeHasJSDoc(node); }); - ts.Debug.assert(classElement && isClassElementHasJSDoc(classElement)); + ts.Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); return classElement; } })(codefix = ts.codefix || (ts.codefix = {})); @@ -143104,11 +143381,11 @@ var ts; var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, 1 /* NoTruncation */); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */) : undefined; } return typeNode || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } @@ -144238,7 +144515,7 @@ var ts; (function (codefix) { var fixId = "fixMissingCallParentheses"; var errorCodes = [ - ts.Diagnostics.This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -146969,7 +147246,7 @@ var ts; 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 flags = ts.getSyntacticModifierFlags(exportNode); + var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ExportDefault */ : 0 /* None */); var wasDefault = !!(flags & 512 /* Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { @@ -146997,6 +147274,11 @@ var ts; ts.Debug.assert(!wasDefault, "Can't have a default flag here"); return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } + case 267 /* ExportAssignment */: { + var node = exportNode; + var exp = node.expression; + return node.isExportEquals ? undefined : { exportNode: node, exportName: exp, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol }; + } default: return undefined; } @@ -147008,7 +147290,14 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + 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]))); + } + else { + changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + } } else { var exportKeyword = ts.Debug.checkDefined(ts.findModifier(exportNode, 92 /* ExportKeyword */), "Should find an export keyword in modifier list"); @@ -147035,7 +147324,7 @@ var ts; changes.insertNodeAfter(exportingSourceFile, exportNode, ts.factory.createExportDefault(ts.factory.createIdentifier(exportName.text))); break; default: - ts.Debug.assertNever(exportNode, "Unexpected exportNode kind " + exportNode.kind); + ts.Debug.fail("Unexpected exportNode kind " + exportNode.kind); } } } @@ -147964,7 +148253,7 @@ var ts; return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } var cursorRequest = length === 0 && invoked; - var startToken = ts.getTokenAtPosition(sourceFile, span.start); + var startToken = ts.findFirstNonJsxWhitespaceToken(sourceFile, span.start); var endToken = ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)); /* If the refactoring command is invoked through a keyboard action it's safe to assume that the user is actively looking for refactoring actions at the span location. As they may not know the exact range that will trigger a refactoring, we expand the @@ -151773,8 +152062,8 @@ var ts; var list = createNode(338 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; addSyntheticNodes(list._children, pos, node.pos, parent); list._children.push(node); pos = node.end; @@ -152216,7 +152505,7 @@ var ts; break; case 161 /* Parameter */: // Only consider parameter properties - if (!ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { break; } // falls through @@ -152797,7 +153086,7 @@ var ts; // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); } function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); @@ -152842,8 +153131,13 @@ 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" - ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind."); - return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + 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); + } } // We didn't already have the file. Fall through and acquire it from the registry. } @@ -152872,7 +153166,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); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); }); program = undefined; // TODO: GH#18217 } @@ -152972,7 +153266,7 @@ var ts; function shouldGetType(sourceFile, node, position) { switch (node.kind) { case 78 /* Identifier */: - return !ts.isLabelName(node) && !ts.isTagName(node); + return !ts.isLabelName(node) && !ts.isTagName(node) && !ts.isConstTypeReference(node.parent); case 202 /* PropertyAccessExpression */: case 158 /* QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` @@ -153138,15 +153432,7 @@ var ts; function getNavigationTree(fileName) { return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); } - function isTsOrTsxFile(fileName) { - var kind = ts.getScriptKind(fileName, host); - return kind === 3 /* TS */ || kind === 4 /* TSX */; - } function getSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return []; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "2020" /* TwentyTwenty */) { @@ -153157,10 +153443,6 @@ var ts; } } function getEncodedSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return { spans: [], endOfLineState: 0 /* None */ }; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "original" /* Original */) { @@ -153251,13 +153533,13 @@ var ts; var formatContext = ts.formatting.getFormatContext(formatOptions, host); return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions, preferences) { + function organizeImports(args, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - ts.Debug.assert(scope.type === "file"); - var sourceFile = getValidSourceFile(scope.fileName); + ts.Debug.assert(args.type === "file"); + var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } @@ -158498,7 +158780,7 @@ var ts; } /*@internal*/ AutoImportProviderProject.getRootFileNames = function (dependencySelection, hostProject, moduleResolutionHost, compilerOptions) { - var _a, _b, _c, _d; + var _a, _b, _c; if (!dependencySelection) { return ts.emptyArray; } @@ -158513,18 +158795,22 @@ var ts; } if (dependencyNames) { var resolutions = ts.map(ts.arrayFrom(dependencyNames.keys()), function (name) { return ts.resolveTypeReferenceDirective(name, rootFileName, compilerOptions, moduleResolutionHost); }); - for (var _e = 0, resolutions_1 = resolutions; _e < resolutions_1.length; _e++) { - var resolution = resolutions_1[_e]; + var program = hostProject.getCurrentProgram(); + var symlinkCache = hostProject.getSymlinkCache(); + for (var _d = 0, resolutions_1 = resolutions; _d < resolutions_1.length; _d++) { + var resolution = resolutions_1[_d]; if (!((_c = resolution.resolvedTypeReferenceDirective) === null || _c === void 0 ? void 0 : _c.resolvedFileName)) continue; - var resolvedFileName = resolution.resolvedTypeReferenceDirective.resolvedFileName; - var fileName = ((_d = moduleResolutionHost.realpath) === null || _d === void 0 ? void 0 : _d.call(moduleResolutionHost, resolvedFileName)) || resolvedFileName; - if (!hostProject.getCurrentProgram().getSourceFile(fileName) && !hostProject.getCurrentProgram().getSourceFile(resolvedFileName)) { - rootNames = ts.append(rootNames, fileName); + var _e = resolution.resolvedTypeReferenceDirective, resolvedFileName = _e.resolvedFileName, originalPath = _e.originalPath; + if (!program.getSourceFile(resolvedFileName) && (!originalPath || !program.getSourceFile(originalPath))) { + rootNames = ts.append(rootNames, resolvedFileName); // Avoid creating a large project that would significantly slow down time to editor interactivity if (dependencySelection === 2 /* Auto */ && rootNames.length > this.maxDependencies) { return ts.emptyArray; } + if (originalPath) { + symlinkCache.setSymlinkedDirectoryFromSymlinkedFile(originalPath, resolvedFileName); + } } } } @@ -163616,7 +163902,7 @@ var ts; Session.prototype.mapDefinitionInfoLocations = function (definitions, project) { return definitions.map(function (info) { var newDocumentSpan = getMappedDocumentSpan(info, project); - return !newDocumentSpan ? info : __assign(__assign({}, newDocumentSpan), { containerKind: info.containerKind, containerName: info.containerName, kind: info.kind, name: info.name }); + return !newDocumentSpan ? info : __assign(__assign(__assign({}, newDocumentSpan), { containerKind: info.containerKind, containerName: info.containerName, kind: info.kind, name: info.name }), info.unverified && { unverified: info.unverified }); }); }; Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) { @@ -163674,7 +163960,7 @@ var ts; }; Session.prototype.mapDefinitionInfo = function (definitions, project) { var _this = this; - return definitions.map(function (def) { return _this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project); }); + return definitions.map(function (def) { return (__assign(__assign({}, _this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project)), def.unverified && { unverified: def.unverified })); }); }; /* * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in @@ -164125,10 +164411,10 @@ var ts; var prefix = args.prefix || ""; var entries = ts.stableSort(ts.mapDefined(completions.entries, function (entry) { if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, sourceDisplay = entry.sourceDisplay, isSnippet = entry.isSnippet, isRecommended = entry.isRecommended, isPackageJsonImport = entry.isPackageJsonImport, data = entry.data; + var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, sourceDisplay = entry.sourceDisplay, isSnippet = entry.isSnippet, isRecommended = entry.isRecommended, isPackageJsonImport = entry.isPackageJsonImport, isImportStatementCompletion = entry.isImportStatementCompletion, data = entry.data; var convertedSpan = replacementSpan ? toProtocolTextSpan(replacementSpan, scriptInfo) : undefined; // Use `hasAction || undefined` to avoid serializing `false`. - return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, isSnippet: isSnippet, hasAction: hasAction || undefined, source: source, sourceDisplay: sourceDisplay, isRecommended: isRecommended, isPackageJsonImport: isPackageJsonImport, data: data }; + return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, isSnippet: isSnippet, hasAction: hasAction || undefined, source: source, sourceDisplay: sourceDisplay, isRecommended: isRecommended, isPackageJsonImport: isPackageJsonImport, isImportStatementCompletion: isImportStatementCompletion, data: data }; } }), function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); if (kind === "completions" /* Completions */) { @@ -164422,11 +164708,14 @@ var ts; return result; } }; - Session.prototype.organizeImports = function (_a, simplifiedResult) { - var scope = _a.scope; - ts.Debug.assert(scope.type === "file"); - var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; - var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file)); + Session.prototype.organizeImports = function (args, simplifiedResult) { + ts.Debug.assert(args.scope.type === "file"); + var _a = this.getFileAndProject(args.scope.args), file = _a.file, project = _a.project; + var changes = project.getLanguageService().organizeImports({ + fileName: file, + skipDestructiveCodeActions: args.skipDestructiveCodeActions, + type: "file", + }, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { return this.mapTextChangesToCodeEdits(changes); } diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index a2ff8fc1ea29a..6195d669a8306 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -540,7 +540,7 @@ declare namespace ts { Override = 16384, HasComputedFlags = 536870912, AccessibilityModifier = 28, - ParameterPropertyModifier = 92, + ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, TypeScriptModifier = 18654, ExportDefault = 513, @@ -563,7 +563,7 @@ declare namespace ts { } export interface JSDocContainer { } - export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; + export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | EmptyStatement | DebuggerStatement | Block | VariableStatement | ExpressionStatement | IfStatement | DoStatement | WhileStatement | ForStatement | ForInStatement | ForOfStatement | BreakStatement | ContinueStatement | ReturnStatement | WithStatement | SwitchStatement | LabeledStatement | ThrowStatement | TryStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; 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; @@ -1380,7 +1380,7 @@ declare namespace ts { readonly containsOnlyTriviaWhiteSpaces: boolean; } export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; - export interface Statement extends Node { + export interface Statement extends Node, JSDocContainer { _statementBrand: any; } export interface NotEmittedStatement extends Statement { @@ -1408,11 +1408,11 @@ declare namespace ts { readonly kind: SyntaxKind.Block; readonly statements: NodeArray; } - export interface VariableStatement extends Statement, JSDocContainer { + export interface VariableStatement extends Statement { readonly kind: SyntaxKind.VariableStatement; readonly declarationList: VariableDeclarationList; } - export interface ExpressionStatement extends Statement, JSDocContainer { + export interface ExpressionStatement extends Statement { readonly kind: SyntaxKind.ExpressionStatement; readonly expression: Expression; } @@ -1493,7 +1493,7 @@ declare namespace ts { readonly statements: NodeArray; } export type CaseOrDefaultClause = CaseClause | DefaultClause; - export interface LabeledStatement extends Statement, JSDocContainer { + export interface LabeledStatement extends Statement { readonly kind: SyntaxKind.LabeledStatement; readonly label: Identifier; readonly statement: Statement; @@ -1613,7 +1613,7 @@ declare namespace ts { readonly parent: ImportEqualsDeclaration; readonly expression: Expression; } - export interface ImportDeclaration extends Statement, JSDocContainer { + export interface ImportDeclaration extends Statement { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; readonly importClause?: ImportClause; @@ -2291,8 +2291,7 @@ declare namespace ts { IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, - InInitialEntityName = 16777216, - InReverseMappedType = 33554432 + InInitialEntityName = 16777216 } export enum TypeFormatFlags { None = 0, @@ -2560,15 +2559,15 @@ declare namespace ts { ObjectLiteral = 128, EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, - ContainsSpread = 1024, - ReverseMapped = 2048, - JsxAttributes = 4096, - MarkerType = 8192, - JSLiteral = 16384, - FreshLiteral = 32768, - ArrayLiteral = 65536, - ObjectRestType = 131072, + ReverseMapped = 1024, + JsxAttributes = 2048, + MarkerType = 4096, + JSLiteral = 8192, + FreshLiteral = 16384, + ArrayLiteral = 32768, ClassOrInterface = 3, + ContainsSpread = 4194304, + ObjectRestType = 8388608, } export interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2682,6 +2681,7 @@ declare namespace ts { type: Type; } export interface SubstitutionType extends InstantiableType { + objectFlags: ObjectFlags; baseType: Type; substitute: Type; } @@ -2706,16 +2706,17 @@ declare namespace ts { export enum InferencePriority { NakedTypeVariable = 1, SpeculativeTuple = 2, - HomomorphicMappedType = 4, - PartialHomomorphicMappedType = 8, - MappedTypeConstraint = 16, - ContravariantConditional = 32, - ReturnType = 64, - LiteralKeyof = 128, - NoConstraints = 256, - AlwaysStrict = 512, - MaxValue = 1024, - PriorityImpliesCombination = 208, + SubstituteSource = 4, + HomomorphicMappedType = 8, + PartialHomomorphicMappedType = 16, + MappedTypeConstraint = 32, + ContravariantConditional = 64, + ReturnType = 128, + LiteralKeyof = 256, + NoConstraints = 512, + AlwaysStrict = 1024, + MaxValue = 2048, + PriorityImpliesCombination = 416, Circularity = -1 } /** @deprecated Use FileExtensionInfo instead. */ @@ -4708,13 +4709,13 @@ declare namespace ts { export {}; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; + export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -4723,30 +4724,46 @@ declare namespace ts { * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResolutionCache, PackageJsonInfoCache { + } /** - * Cached module resolutions per containing directory. + * Cached resolutions per containing directory. * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ - interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + export interface PerDirectoryResolutionCache { + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + clear(): void; + /** + * Updates with the current compilerOptions the cache will operate with. + * This updates the redirects map as well if needed so module resolutions are cached if they can across the projects + */ + update(options: CompilerOptions): void; + } + export interface ModuleResolutionCache extends PerDirectoryResolutionCache, NonRelativeModuleNameResolutionCache, PackageJsonInfoCache { + getPackageJsonInfoCache(): PackageJsonInfoCache; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ - interface NonRelativeModuleNameResolutionCache { + export interface NonRelativeModuleNameResolutionCache extends PackageJsonInfoCache { getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } - interface PerModuleNameCache { + export interface PackageJsonInfoCache { + clear(): void; + } + export interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } - function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; - function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; + export function createTypeReferenceDirectiveResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions, packageJsonInfoCache?: PackageJsonInfoCache): TypeReferenceDirectiveResolutionCache; + export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; + export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export {}; } declare namespace ts { /** @@ -5202,9 +5219,9 @@ declare namespace ts { interface SolutionBuilderWithWatchHost extends SolutionBuilderHostBase, WatchHost { } interface SolutionBuilder { - build(project?: string, cancellationToken?: CancellationToken): ExitStatus; + build(project?: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; clean(project?: string): ExitStatus; - buildReferences(project: string, cancellationToken?: CancellationToken): ExitStatus; + buildReferences(project: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; cleanReferences(project?: string): ExitStatus; getNextInvalidatedProject(cancellationToken?: CancellationToken): InvalidatedProject | undefined; } @@ -5650,7 +5667,7 @@ declare namespace ts { applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; + organizeImports(args: OrganizeImportsArgs, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; @@ -5667,7 +5684,9 @@ declare namespace ts { type: "file"; fileName: string; } - type OrganizeImportsScope = CombinedCodeFixScope; + interface OrganizeImportsArgs extends CombinedCodeFixScope { + skipDestructiveCodeActions?: boolean; + } type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; interface GetCompletionsAtPositionOptions extends UserPreferences { /** @@ -6196,6 +6215,7 @@ declare namespace ts { isRecommended?: true; isFromUncheckedFile?: true; isPackageJsonImport?: true; + isImportStatementCompletion?: true; /** * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, * that allows TS Server to look up the symbol represented by the completion item, disambiguating @@ -6517,8 +6537,23 @@ declare namespace ts { * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file */ + /**@deprecated pass scriptKind for correctness */ releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @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 + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind): void; + /** + * @deprecated pass scriptKind for correctness */ releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind): void; reportStats(): string; } type DocumentRegistryBucketKey = string & { @@ -7154,6 +7189,7 @@ declare namespace ts.server.protocol { type OrganizeImportsScope = GetCombinedCodeFixScope; interface OrganizeImportsRequestArgs { scope: OrganizeImportsScope; + skipDestructiveCodeActions?: boolean; } interface OrganizeImportsResponse extends Response { body: readonly FileCodeEdits[]; @@ -7389,7 +7425,7 @@ declare namespace ts.server.protocol { * Definition response message. Gives text range for definition. */ interface DefinitionResponse extends Response { - body?: FileSpanWithContext[]; + body?: DefinitionInfo[]; } interface DefinitionInfoAndBoundSpanResponse extends Response { body?: DefinitionInfoAndBoundSpan; @@ -8378,9 +8414,14 @@ declare namespace ts.server.protocol { isFromUncheckedFile?: true; /** * If true, this completion was for an auto-import of a module not yet in the program, but listed - * in the project package.json. + * in the project package.json. Used for telemetry reporting. */ isPackageJsonImport?: true; + /** + * If true, this completion was an auto-import-style completion of an import statement (i.e., the + * module specifier was inserted along with the imported identifier). Used for telemetry reporting. + */ + isImportStatementCompletion?: true; /** * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, * that allows TS Server to look up the symbol represented by the completion item, disambiguating diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 086d3b2f2a99b..b57f7c3ca2326 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -290,7 +290,7 @@ var ts; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-beta"; + ts.version = "4.3.1-rc"; /* @internal */ var Comparison; (function (Comparison) { @@ -2856,11 +2856,11 @@ var ts; this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : - this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" : + this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; - var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0; + var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); } }, @@ -3881,7 +3881,7 @@ var ts; }; } var reverseMappedProperties = {}; - if (objectFlags & 2048 /* ReverseMapped */) { + if (objectFlags & 1024 /* ReverseMapped */) { var reverseMappedType = type; reverseMappedProperties = { reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id, @@ -4422,7 +4422,7 @@ var ts; 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. - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 18654] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; @@ -4623,7 +4623,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; - NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -4976,6 +4975,9 @@ var ts; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags + // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check + // for a certain TypeFlags value to determine their meaning. var ObjectFlags; (function (ObjectFlags) { ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; @@ -4988,50 +4990,59 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; - ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; - ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; - ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; - ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; - ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; - ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 1024] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 2048] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 4096] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 8192] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 16384] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ArrayLiteral"] = 32768] = "ArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 262144] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; + ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 1048576] = "CouldContainTypeVariablesComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; + ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 2097152] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags"; + // Object flags that uniquely identify the kind of ObjectType /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; + ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask"; + // Flags that require TypeFlags.Object + ObjectFlags[ObjectFlags["ContainsSpread"] = 4194304] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 8388608] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone"; + // Flags that require TypeFlags.Object and ObjectFlags.Reference /* @internal */ - ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated"; /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists"; + // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; + ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; + ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; - // Object flags that uniquely identify the kind of ObjectType + ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + // Flags that require TypeFlags.Union + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 67108864] = "ContainsIntersections"; + // Flags that require TypeFlags.Intersection /* @internal */ - ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask"; + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 67108864] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 134217728] = "IsNeverIntersection"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -5105,16 +5116,17 @@ var ts; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple"; - InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType"; - InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType"; - InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint"; - InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional"; - InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType"; - InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof"; - InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict"; - InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue"; - InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination"; + InferencePriority[InferencePriority["SubstituteSource"] = 4] = "SubstituteSource"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 8] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 16] = "PartialHomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 32] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ContravariantConditional"] = 64] = "ContravariantConditional"; + InferencePriority[InferencePriority["ReturnType"] = 128] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 256] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 512] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 1024] = "AlwaysStrict"; + InferencePriority[InferencePriority["MaxValue"] = 2048] = "MaxValue"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 416] = "PriorityImpliesCombination"; InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); /* @internal */ @@ -8051,7 +8063,7 @@ var ts; A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), - An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), @@ -8077,6 +8089,7 @@ var ts; A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), @@ -8163,7 +8176,7 @@ var ts; Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."), - The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."), + The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8205,6 +8218,7 @@ var ts; The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), + Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."), 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), @@ -8453,14 +8467,13 @@ var ts; The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), - Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), @@ -8483,17 +8496,17 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), @@ -8578,7 +8591,7 @@ var ts; Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), @@ -8586,14 +8599,14 @@ var ts; _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), - A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), @@ -8655,7 +8668,7 @@ var ts; The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), - This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_2774", "This condition will always return true since this function appears to always be defined. Did you mean to call it instead?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), @@ -8682,7 +8695,7 @@ var ts; The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), - This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined_2801", "This condition will always return true since this '{0}' appears to always be defined."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), @@ -8691,6 +8704,9 @@ var ts; This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), + Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), + Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), 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}'."), @@ -8788,7 +8804,7 @@ var ts; This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), - This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_becaus_4115", "This parameter property must be rewritten as a property declaration with an 'override' modifier because it overrides a member in base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), 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."), @@ -8824,7 +8840,7 @@ var ts; Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), - Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), @@ -8837,12 +8853,14 @@ var ts; Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), - A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -9066,7 +9084,11 @@ var ts; Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), - Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -9114,6 +9136,7 @@ var ts; _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), 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."), @@ -9155,7 +9178,7 @@ var ts; Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -9195,7 +9218,7 @@ var ts; JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), @@ -9880,11 +9903,11 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; /* @internal */ - function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { - if (stopAtComments === void 0) { stopAtComments = false; } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (ts.positionIsSynthesized(pos)) { return pos; } + var canConsumeStar = false; // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -9899,6 +9922,7 @@ var ts; if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case 9 /* tab */: case 11 /* verticalTab */: @@ -9918,6 +9942,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { @@ -9929,6 +9954,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } break; @@ -9938,12 +9964,21 @@ var ts; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; case 35 /* hash */: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42 /* asterisk */: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -11994,7 +12029,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; + return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -12310,7 +12345,7 @@ var ts; if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } ts.getNameOfDeclaration = getNameOfDeclaration; /*@internal*/ @@ -12865,7 +12900,7 @@ var ts; ts.isModifierKind = isModifierKind; /* @internal */ function isParameterPropertyModifier(kind) { - return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + return !!(ts.modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */); } ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ @@ -13825,7 +13860,9 @@ var ts; } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { @@ -14078,7 +14115,9 @@ var ts; if (node.kind === 338 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ false, isInJSDoc(node)); } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -15513,6 +15552,10 @@ var ts; return node.kind === 177 /* TypeQuery */; } ts.isPartOfTypeQuery = isPartOfTypeQuery; + function isNamespaceReexportDeclaration(node) { + return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 273 /* ExternalModuleReference */; } @@ -16125,6 +16168,7 @@ var ts; parent.kind === 267 /* ExportAssignment */ || parent.kind === 164 /* PropertyDeclaration */ || parent.kind === 234 /* ExpressionStatement */ && node.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 243 /* ReturnStatement */ || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) { return parent; @@ -19325,6 +19369,10 @@ var ts; return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; + function getUseDefineForClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === 99 /* ESNext */ : compilerOptions.useDefineForClassFields; + } + ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return oldOptions !== newOptions && ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); @@ -19396,19 +19444,33 @@ var ts; } (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); } - } + }, + setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { + this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); + var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var cache = createSymlinkCache(cwd, getCanonicalFileName); - var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { - return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + var symlinks = ts.flatMap(files, function (sf) { + var pairs = sf.resolvedModules && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedModules.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) ? [res.resolvedFileName, res.originalPath] : undefined; + })); + return ts.concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] : undefined; }))); - })); + }); for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); @@ -20405,7 +20467,11 @@ var ts; var ts; (function (ts) { function createParenthesizerRules(factory) { + var binaryLeftOperandParenthesizerCache; + var binaryRightOperandParenthesizerCache; return { + getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName, @@ -20426,6 +20492,24 @@ var ts; parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType, parenthesizeTypeArguments: parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); }; + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); }; + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } /** * Determines whether the operand to a BinaryExpression needs to be parenthesized. * @@ -20754,6 +20838,8 @@ var ts; } ts.createParenthesizerRules = createParenthesizerRules; ts.nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; }, + getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; }, parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; }, parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; }, parenthesizeExpressionOfComputedPropertyName: ts.identity, @@ -21695,6 +21781,7 @@ var ts; case 155 /* BigIntKeyword */: case 141 /* NeverKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 147 /* StringKeyword */: case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: @@ -21777,15 +21864,15 @@ var ts; if (flags & 32 /* Static */) { result.push(createModifier(123 /* StaticKeyword */)); } + if (flags & 16384 /* Override */) { + result.push(createModifier(156 /* OverrideKeyword */)); + } if (flags & 64 /* Readonly */) { result.push(createModifier(142 /* ReadonlyKeyword */)); } if (flags & 256 /* Async */) { result.push(createModifier(129 /* AsyncKeyword */)); } - if (flags & 16384 /* Override */) { - result.push(createModifier(156 /* OverrideKeyword */)); - } return result; } // @@ -21857,7 +21944,7 @@ var ts; propagateChildFlags(node.questionToken); if (questionToken) node.transformFlags |= 1 /* ContainsTypeScript */; - if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */) + if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */) node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) node.transformFlags |= 512 /* ContainsES2015 */; @@ -22524,7 +22611,7 @@ var ts; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { var node = createBaseBindingLikeDeclaration(199 /* BindingElement */, /*decorators*/ undefined, - /*modifiers*/ undefined, name, initializer); + /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= @@ -29360,6 +29447,7 @@ var ts; case 324 /* JSDocPrivateTag */: case 325 /* JSDocProtectedTag */: case 326 /* JSDocReadonlyTag */: + case 321 /* JSDocDeprecatedTag */: return visitNode(cbNode, node.tagName) || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); case 340 /* PartiallyEmittedExpression */: @@ -31450,19 +31538,21 @@ var ts; function parseParameterWorker(inOuterAwaitContext) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); + // 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(); if (token() === 107 /* ThisKeyword */) { - var node_1 = factory.createParameterDeclaration( - /*decorators*/ undefined, + var node_1 = factory.createParameterDeclaration(decorators, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); + if (decorators) { + parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } return withJSDoc(finishNode(node_1, pos), hasJSDoc); } - // 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 savedTopLevel = topLevel; topLevel = false; var modifiers = parseModifiers(); @@ -33748,12 +33838,13 @@ var ts; // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var openBracePosition = scanner.getTokenPos(); if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { var multiLine = scanner.hasPrecedingLineBreak(); var statements = parseList(1 /* BlockStatements */, parseStatement); parseExpectedMatchingBrackets(18 /* OpenBraceToken */, 19 /* CloseBraceToken */, openBracePosition); - var result = finishNode(factory.createBlock(statements, multiLine), pos); + var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); if (token() === 62 /* EqualsToken */) { parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); nextToken(); @@ -33762,7 +33853,7 @@ var ts; } else { var statements = createMissingList(); - return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -33789,11 +33880,13 @@ var ts; } function parseEmptyStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(26 /* SemicolonToken */); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(98 /* IfKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); @@ -33801,10 +33894,11 @@ var ts; parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var thenStatement = parseStatement(); var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(89 /* DoKeyword */); var statement = parseStatement(); parseExpected(114 /* WhileKeyword */); @@ -33817,20 +33911,22 @@ var ts; // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. parseOptional(26 /* SemicolonToken */); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(114 /* WhileKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(96 /* ForKeyword */); var awaitToken = parseOptionalToken(130 /* AwaitKeyword */); parseExpected(20 /* OpenParenToken */); @@ -33866,34 +33962,37 @@ var ts; parseExpected(21 /* CloseParenToken */); node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(kind === 242 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); var node = kind === 242 /* BreakStatement */ ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(104 /* ReturnKeyword */); var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(115 /* WithKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { var pos = getNodePos(); @@ -33922,17 +34021,19 @@ var ts; } function parseSwitchStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(106 /* SwitchKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { // ThrowStatement[Yield] : // throw [no LineTerminator here]Expression[In, ?Yield]; var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(108 /* ThrowKeyword */); // Because of automatic semicolon insertion, we need to report error if this // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' @@ -33945,11 +34046,12 @@ var ts; expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } // TODO: Review for error recovery function parseTryStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(110 /* TryKeyword */); var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -33960,7 +34062,7 @@ var ts; parseExpected(95 /* FinallyKeyword */); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { var pos = getNodePos(); @@ -33979,9 +34081,10 @@ var ts; } function parseDebuggerStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(86 /* DebuggerKeyword */); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement() { // Avoiding having to do the lookahead for a labeled statement by just trying to parse @@ -35368,7 +35471,6 @@ var ts; state = 2 /* SavingComments */; var commentEnd = scanner.getStartPos(); var linkStart = scanner.getTextPos() - 1; - // TODO: redo here var link = parseJSDocLink(linkStart); if (link) { if (!linkEnd) { @@ -35570,8 +35672,9 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */ || !previousWhitespace && state === 2 /* SavingComments */) { - // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace + if (state === 3 /* SavingBackticks */ + || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace comments.push(scanner.getTokenText()); break; } @@ -35648,6 +35751,10 @@ var ts; return comments.join(""); } } + function isNextJSDocTokenWhitespace() { + var next = nextTokenJSDoc(); + return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */; + } function parseJSDocLink(start) { if (!tryParse(parseJSDocLinkPrefix)) { return undefined; @@ -37151,8 +37258,8 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - /* @internal */ - ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsWithoutBuild = [ + // CommandLine only options { name: "all", type: "boolean", @@ -37938,7 +38045,9 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins }, - ]); + ]; + /* @internal */ + ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsWithoutBuild); /* @internal */ ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); /* @internal */ @@ -37953,8 +38062,7 @@ var ts; ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) { return ts.hasProperty(option, "transpileOptionValue"); }); - /* @internal */ - ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsOnlyBuild = [ { name: "verbose", shortName: "v", @@ -37982,7 +38090,9 @@ var ts; description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean" } - ]); + ]; + /* @internal */ + ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsOnlyBuild); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -38036,6 +38146,10 @@ var ts; return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations)); } ts.getOptionsNameMap = getOptionsNameMap; + var compilerOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; /* @internal */ ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, @@ -38097,6 +38211,10 @@ var ts; return option.name; } function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { + var _a; + if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -38251,6 +38369,7 @@ var ts; } /*@internal*/ ts.compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -38283,7 +38402,12 @@ var ts; function getBuildOptionsNameMap() { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts)); } + var buildOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap: getOptionsNameMap + }; var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: ts.buildOpts, unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, @@ -40034,13 +40158,24 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) { var traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined; + var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -40063,6 +40198,8 @@ var ts; trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); } } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -40073,17 +40210,31 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary: primary, + resolvedFileName: resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId: packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, result); + if (traceEnabled) + traceResult(result); + return result; + function traceResult(result) { + var _a; + if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { // Check primary library paths if (typeRoots && typeRoots.length) { @@ -40113,20 +40264,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = void 0; + var result_4; if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); - result = searchResult && searchResult.value; + result_4 = searchResult && searchResult.value; } else { var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; - result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); - } - var resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); } - return resolvedFile; + return resolvedTypeScriptOnly(result_4); } else { if (traceEnabled) { @@ -40181,22 +40328,21 @@ var ts; return result; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName); - } - ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ function createCacheWithRedirects(options) { var ownMap = new ts.Map(); var redirectsMap = new ts.Map(); return { - ownMap: ownMap, + getOwnMap: getOwnMap, redirectsMap: redirectsMap, getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, clear: clear, setOwnOptions: setOwnOptions, setOwnMap: setOwnMap }; + function getOwnMap() { + return ownMap; + } function setOwnOptions(newOptions) { options = newOptions; } @@ -40222,26 +40368,88 @@ var ts; } } ts.createCacheWithRedirects = createCacheWithRedirects; - /*@internal*/ - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap }; + function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + var cache; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear }; + function getPackageJsonInfo(packageJsonPath) { + return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + if (!options.configFile) + return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + // The own map will be for projectCompilerOptions + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + // Set correct own map + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + var ref = { + sourceFile: options.configFile, + commandLine: { options: options } + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options); + } + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) { + return { + getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, + clear: clear, + update: update, + }; + function clear() { + directoryToModuleNameMap.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap); + } function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); }); } + } + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + var preDirectoryResolutionCache = 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; } }); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + packageJsonInfoCache.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); + } function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } - function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { - var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - var result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; - } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); return { get: get, set: set }; @@ -40308,7 +40516,17 @@ var ts; } } } - ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + ts.createModuleResolutionCache = createModuleResolutionCache; + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache.clear(); + } + } + ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache) { var containingDirectory = ts.getDirectoryPath(containingFile); var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -40586,7 +40804,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; 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, state.resultFromCache); function tryResolve(extensions) { @@ -40646,7 +40864,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -40679,8 +40897,9 @@ var ts; * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo" * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo" */ + /* @internal */ function parseNodeModuleFromPath(resolved) { - var path = ts.normalizePath(resolved.path); + var path = ts.normalizePath(resolved); var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; @@ -40692,6 +40911,7 @@ var ts; } return path.slice(0, indexAfterPackageName); } + ts.parseNodeModuleFromPath = parseNodeModuleFromPath; function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; @@ -40775,21 +40995,43 @@ var ts; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c; var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) + trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) + trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + var directoryExists = ts.directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = ts.readJson(packageJsonPath, host); if (traceEnabled) { trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists); // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results state.failedLookupLocations.push(packageJsonPath); } @@ -41038,7 +41280,7 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath @@ -41079,13 +41321,13 @@ var ts; * This is the minumum code needed to expose that functionality; the rest is in the host. */ /* @internal */ - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { 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 state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache); } @@ -41731,6 +41973,7 @@ var ts; } if (node.kind === 298 /* SourceFile */) { node.flags |= emitFlags; + node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -43048,9 +43291,9 @@ var ts; var saveCurrentFlow = currentFlow; for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { var typeAlias = delayedTypeAliases_1[_i]; - var host = ts.getJSDocHost(typeAlias); - container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); })) || file; - blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file; + var host = typeAlias.parent.parent; + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -43636,8 +43879,8 @@ var ts; } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + // Incorrect export assignment in some sort of block construct + bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node)); } else { var flags = ts.exportAssignmentIsAlias(node) @@ -44815,6 +45058,7 @@ var ts; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -44823,7 +45067,7 @@ var ts; var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384 /* FreshLiteral */; var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); @@ -45010,6 +45254,7 @@ var ts; return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, + getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, argumentCount) { return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */); @@ -45181,14 +45426,14 @@ var ts; var autoType = createIntrinsicType(1 /* Any */, "any"); var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); - var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */); + var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 131072 /* ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -45214,7 +45459,7 @@ var ts; var voidType = createIntrinsicType(16384 /* Void */, "void"); var neverType = createIntrinsicType(131072 /* Never */, "never"); var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -45226,7 +45471,7 @@ var ts; var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -45235,7 +45480,7 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */; + anyFunctionType.objectFlags |= 524288 /* NonInferrableType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -45897,7 +46142,7 @@ var ts; } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property - return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -45925,7 +46170,7 @@ var ts; return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); @@ -46060,7 +46305,7 @@ var ts; case 164 /* PropertyDeclaration */: // static properties in classes introduce temporary variables if (ts.hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + return target < 99 /* ESNext */ || !useDefineForClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -46445,7 +46690,7 @@ var ts; } // Perform extra checks only if error reporting was requested if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* 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. @@ -46776,8 +47021,7 @@ var ts; } } function getDeclarationOfAliasSymbol(symbol) { - var _a; - return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(isAliasSymbolDeclaration); + return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration); } /** * An alias symbol is created by one of the following declarations: @@ -46792,6 +47036,7 @@ var ts; * module.exports = * {} * {name: } + * const { x } = require ... */ function isAliasSymbolDeclaration(node) { return node.kind === 261 /* ImportEqualsDeclaration */ @@ -47022,7 +47267,7 @@ var ts; return undefined; } var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -48098,7 +48343,7 @@ var ts; var _loop_8 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } } @@ -48113,7 +48358,7 @@ var ts; // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred // to one another anyway) - if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) { + if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } break; @@ -48145,7 +48390,7 @@ var ts; if (typeof state_2 === "object") return state_2.value; } - return callback(globals); + return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace @@ -48165,11 +48410,11 @@ var ts; /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) */ - function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols, ignoreQualification); + var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables.pop(); return result; } @@ -48187,7 +48432,7 @@ var ts; !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols, ignoreQualification) { + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { // If symbol is directly available by its name in the symbol table if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; @@ -48200,6 +48445,8 @@ var ts; && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // If we're looking up a local name to reference directly, omit namespace reexports, otherwise when we're trawling through an export list to make a dotted name, we can keep it + && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */))) { @@ -48302,7 +48549,7 @@ var ts; return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -48563,7 +48810,7 @@ var ts; return flags & 814775659 /* NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { - return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */)); + return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* Object */) && !!(ts.getObjectFlags(type) & 16777216 /* IsClassInstanceClone */))); } function createNodeBuilder() { return { @@ -49176,7 +49423,7 @@ var ts; } if (resolvedType.stringIndexInfo) { var indexSignature = void 0; - if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + if (resolvedType.objectFlags & 1024 /* ReverseMapped */) { indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context)); } else { @@ -49220,10 +49467,23 @@ var ts; } return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + // Use placeholders for reverse mapped types we've either already descended into, or which + // are nested reverse mappings within a mapping over a non-anonymous type. The later is a restriction mostly just to + // reduce the blowup in printback size from doing, eg, a deep reverse mapping over `Window`. + // Since anonymous types usually come from expressions, this allows us to preserve the output + // for deep mappings which likely come from expressions, while truncating those parts which + // come from mappings over library functions. + return !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) + && (ts.contains(context.reverseMappedStack, propertySymbol) + || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0]) + && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16 /* Anonymous */))); + } function addPropertyToElementList(propertySymbol, context, typeElements) { var _a; var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */); - var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; @@ -49255,16 +49515,20 @@ var ts; } } else { - var savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; var propertyTypeNode = void 0; - if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } } - context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; @@ -49305,25 +49569,25 @@ var ts; var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); /** Map from type reference identifier text to [type, index in `result` where the type node is] */ var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; - var result_4 = []; + var result_5 = []; var i = 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result_4.push(typeNode_1); + result_5.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result_4.push(typeNode); + result_5.push(typeNode); if (seenNames && ts.isIdentifierTypeReference(typeNode)) { - seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]); + seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]); } } } @@ -49345,13 +49609,13 @@ var ts; })) { for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var _a = types_3[_i], type = _a[0], resultIndex = _a[1]; - result_4[resultIndex] = typeToTypeNodeHelper(type, context); + result_5[resultIndex] = typeToTypeNodeHelper(type, context); } } }); context.flags = saveContextFlags; } - return result_4; + return result_5; } } function typesAreSameReference(a, b) { @@ -49685,7 +49949,7 @@ var ts; // specifier preference var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map()); links.specifierCache.set(contextFile.path, specifier); } @@ -49975,13 +50239,13 @@ var ts; function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { if (type !== errorType && enclosingDeclaration) { var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) { // try to reuse the existing annotation var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); - if (result_5) { - return result_5; + var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_6) { + return result_6; } } } @@ -49998,10 +50262,14 @@ var ts; function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { if (type !== errorType && context.enclosingDeclaration) { var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); - if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) { + var annotated = getTypeFromTypeNode(annotation); + var thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -51755,7 +52023,7 @@ var ts; var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= 131072 /* ObjectRestType */; + result.objectFlags |= 8388608 /* ObjectRestType */; return result; } function isGenericTypeWithUndefinedConstraint(type) { @@ -52063,6 +52331,22 @@ var ts; } ; } + /** Create a synthetic property access flow node after the last statement of the file */ + function getFlowTypeFromCommonJSExport(symbol) { + var file = ts.getSourceFileOfNode(symbol.declarations[0]); + var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName); + var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); }); + var reference = areAllModuleExports + ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName) + : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + ts.setParent(reference.expression.expression, reference.expression); + } + ts.setParent(reference.expression, reference); + ts.setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); + } function getFlowTypeInConstructor(symbol, constructor) { var accessName = ts.startsWith(symbol.escapedName, "__#") ? ts.factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) @@ -52178,7 +52462,7 @@ var ts; mergeSymbolTable(exports, s.exports); } var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - type.objectFlags |= 16384 /* JSLiteral */; + type.objectFlags |= 8192 /* JSLiteral */; return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { @@ -52279,9 +52563,9 @@ 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.stringIndexInfo, exportedType.numberIndexInfo); - result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + result.objectFlags |= (ts.getObjectFlags(type) & 8192 /* JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { - result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type + result.objectFlags |= 16777216 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type } return result; } @@ -52340,7 +52624,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -52364,7 +52648,7 @@ var ts; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -52383,7 +52667,7 @@ var ts; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -52640,38 +52924,31 @@ var ts; if (writing === void 0) { writing = false; } var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); // For write operations, prioritize type annotations on the setter - if (writing) { - var setterParameterType_1 = getAnnotatedAccessorType(setter); - if (setterParameterType_1) { - var flags = ts.getCheckFlags(symbol); - if (flags & 1 /* Instantiated */) { - var links = getSymbolLinks(symbol); - return instantiateType(setterParameterType_1, links.mapper); - } - return setterParameterType_1; - } + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); } // Else defer to the getter type if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } // Try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + var getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + if (setterType) { + return setterType; } // If there are no specified types, try to infer it from the body of the get accessor if it exists. if (getter && getter.body) { - return getReturnTypeFromBody(getter); + var returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); } // Otherwise, fall back to 'any'. if (setter) { @@ -52688,6 +52965,13 @@ var ts; return anyType; } return undefined; + function instantiateTypeIfNeeded(type, symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); + } + return type; + } } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); @@ -52752,14 +53036,16 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); + var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontResolveAlias*/ true); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 111551 /* Value */ - ? getTypeOfSymbol(targetSymbol) - : errorType; + links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -54363,6 +54649,12 @@ var ts; } } } + function replaceIndexedAccess(instantiable, type, replacement) { + // map type.indexType to 0 + // map type.objectType to `[TReplacement]` + // thus making the indexed access `[TReplacement][0]` or `TReplacement` + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } function getIndexInfoOfIndexSymbol(indexSymbol, indexKind) { var declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); if (!declaration) @@ -54383,8 +54675,21 @@ var ts; inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ + && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ + && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) { + // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is + // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of + // type identities produced, we simplify such indexed access occurences + var newTypeParam = type.constraintType.type.objectType; + var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.mappedType = newMappedType; + inferredProp.constraintType = getIndexType(newTypeParam); + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -54598,7 +54903,7 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 2048 /* ReverseMapped */) { + else if (type.objectFlags & 1024 /* ReverseMapped */) { resolveReverseMappedTypeMembers(type); } else if (type.objectFlags & 16 /* Anonymous */) { @@ -55017,6 +55322,7 @@ var ts; return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b; var singleProp; var propSet; var indexTypes; @@ -55025,8 +55331,9 @@ var ts; var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var current = _a[_i]; + var mergedInstantiations = false; + for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) { + var current = _c[_i]; var type = getApparentType(current); if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); @@ -55042,13 +55349,25 @@ var ts; singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new ts.Map(); - propSet.set(getSymbolId(singleProp), singleProp); + var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + // If the symbols are instances of one another with identical types - consider the symbols + // equivalent and just use the first one, which thus allows us to avoid eliding private + // members when intersecting a (this-)instantiations of a class with it's raw base or another instance + if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 /* True */ : 0 /* False */; }) === -1 /* True */) { + // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used + // to do when we recorded multiple distinct symbols so that we still get, eg, `Array.length` printed + // back and not `Array.length` when we're looking at a `.length` access on a `string[] | number[]` + mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - var id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new ts.Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + var id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | @@ -55066,7 +55385,7 @@ var ts; checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0); indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304 /* ContainsSpread */)) { checkFlags |= 32 /* WritePartial */; indexTypes = ts.append(indexTypes, undefinedType); } @@ -55082,7 +55401,19 @@ var ts; return undefined; } if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + // No symbol from a union/intersection should have a `.parent` set (since unions/intersections don't act as symbol parents) + // Unless that parent is "reconstituted" from the "first value declaration" on the symbol (which is likely different than its instantiated parent!) + // They also have a `.containingType` set, which affects some services endpoints behavior, like `getRootSymbol` + var clone_1 = createSymbolWithType(singleProp, singleProp.type); + clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent; + clone_1.containingType = containingType; + clone_1.mapper = singleProp.mapper; + return clone_1; + } + else { + return singleProp; + } } var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; @@ -55091,8 +55422,8 @@ var ts; var propTypes = []; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; - for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { - var prop = props_1[_b]; + for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { + var prop = props_1[_d]; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } @@ -55169,15 +55500,15 @@ var ts; * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. */ function getReducedType(type) { - if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 67108864 /* ContainsIntersections */) { return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); } else if (type.flags & 2097152 /* Intersection */) { - if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { - type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); + if (!(type.objectFlags & 67108864 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 67108864 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 134217728 /* IsNeverIntersection */ : 0); } - return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + return type.objectFlags & 134217728 /* IsNeverIntersection */ ? neverType : type; } return type; } @@ -55207,7 +55538,7 @@ var ts; return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); } function elaborateNeverIntersection(errorInfo, type) { - if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + if (type.flags & 2097152 /* Intersection */ && ts.getObjectFlags(type) & 134217728 /* IsNeverIntersection */) { var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); @@ -55364,6 +55695,9 @@ var ts; } return false; } + function isOptionalPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && node.questionToken; + } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; @@ -55518,8 +55852,7 @@ var ts; if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) return undefined; var typeTag = ts.getJSDocTypeTag(node); - var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); @@ -55884,6 +56217,17 @@ var ts; else if (grandParent.kind === 160 /* TypeParameter */ && grandParent.parent.kind === 191 /* MappedType */) { inferences = ts.append(inferences, keyofConstraintType); } + // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends + // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template + // of the check type's mapped type + else if (grandParent.kind === 191 /* MappedType */ && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 185 /* ConditionalType */ && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 191 /* MappedType */ && + grandParent.parent.checkType.type) { + var checkMappedType_1 = grandParent.parent.checkType; + var nodeType = getTypeFromTypeNode(checkMappedType_1.type); + inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); + } } } } @@ -55957,7 +56301,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 3670016 /* PropagatingFlags */; + return result & 917504 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -56086,11 +56430,21 @@ var ts; ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } + // We refrain from associating a local type alias with an instantiation of a top-level type alias + // because the local alias may end up being referenced in an inferred return type where it is not + // accessible--which in turn may lead to a large structural expansion of the type when generating + // a .d.ts file. See #43622 for an example. var aliasSymbol = getAliasSymbolForTypeNode(node); - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol) { + var _a; + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias); + return !!(declaration && ts.getContainingFunction(declaration)); + } function getTypeReferenceName(node) { switch (node.kind) { case 174 /* TypeReference */: @@ -56186,9 +56540,17 @@ var ts; } function getConditionalFlowTypeOfType(type, node) { var constraints; + var covariant = true; while (node && !ts.isStatement(node) && node.kind !== 312 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { + // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but + // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax + if (parent.kind === 161 /* Parameter */) { + covariant = !covariant; + } + // Always substitute on type parameters, regardless of variance, since even + // in contravariant positions, they may rely on substituted constraints to be valid + if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -56780,7 +57142,7 @@ var ts; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; } else { @@ -56982,8 +57344,8 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | - (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 67108864 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } function getUnionOrIntersectionTypePredicate(signatures, kind) { @@ -57041,7 +57403,7 @@ var ts; var typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id; + "#" + origin.type.id + "|" + getTypeListId(types); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { @@ -57168,7 +57530,7 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -57177,7 +57539,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -57206,7 +57568,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -57604,7 +57966,7 @@ var ts; if (noImplicitAny) { return false; // Flag is meaningless under `noImplicitAny` mode } - if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + if (ts.getObjectFlags(type) & 8192 /* JSLiteral */) { return true; } if (type.flags & 1048576 /* Union */) { @@ -57818,6 +58180,13 @@ var ts; } return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) { + type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ | + (isGenericObjectType(type.substitute) || isGenericObjectType(type.baseType) ? 8388608 /* IsGenericObjectType */ : 0); + } + return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); + } return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type) { @@ -57828,6 +58197,13 @@ var ts; } return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) { + type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ | + (isGenericIndexType(type.substitute) || isGenericIndexType(type.baseType) ? 33554432 /* IsGenericIndexType */ : 0); + } + return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); + } return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type); } function isThisTypeParameter(type) { @@ -58085,7 +58461,7 @@ var ts; // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { var isUnwrapped = isTypicalNondistributiveConditional(root); - var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { @@ -58098,7 +58474,7 @@ var ts; // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); } // It's possible for 'infer T' type paramteters to be given uninstantiated constraints when the // those type parameters are used in type references (see getInferredTypeParameterConstraint). For @@ -58355,7 +58731,7 @@ var ts; } } var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return spread; } } @@ -58461,7 +58837,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */ | 4194304 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ @@ -58881,8 +59257,9 @@ var ts; outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || ts.emptyArray; - typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? - ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) : + var allDeclarations_1 = type.objectFlags & 4 /* Reference */ ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) : typeParameters; links.outerTypeParameters = typeParameters; } @@ -58927,7 +59304,7 @@ var ts; return true; } } - return !!ts.forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node) { @@ -58939,6 +59316,9 @@ var ts; getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality case 177 /* TypeQuery */: return true; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + return (!node.type && !!node.body) || !!ts.forEachChild(node, containsReference); } return !!ts.forEachChild(node, containsReference); } @@ -59118,6 +59498,9 @@ var ts; var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; } + if (objectFlags & 1024 /* ReverseMapped */) { + return instantiateReverseMappedType(type, mapper); + } return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; @@ -59167,6 +59550,21 @@ var ts; } return type; } + function instantiateReverseMappedType(type, mapper) { + var innerMappedType = instantiateType(type.mappedType, mapper); + if (!(ts.getObjectFlags(innerMappedType) & 32 /* Mapped */)) { + return type; + } + var innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304 /* Index */)) { + return type; + } + var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); + if (instantiated) { + return instantiated; + } + return type; // Nested invocation of `inferTypeForHomomorphicMappedType` or the `source` instantiated into something unmappable + } function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -60082,7 +60480,7 @@ var ts; return false; } function isIgnoredJsxProperty(source, sourceProp) { - return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); + return ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { while (true) { @@ -60092,6 +60490,7 @@ var ts; type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; @@ -60409,7 +60808,7 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1 /* True */; } - reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */)); return 0 /* False */; } // Normalize the source and target types: Turn fresh literal types into regular literal types, @@ -60452,8 +60851,8 @@ var ts; if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); + var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -60538,7 +60937,7 @@ var ts; // We suppress recursive intersection property checks because they can generate lots of work when relating // recursive intersections that are structurally similar but not exactly identical. See #37854. if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); inPropertyCheck = false; @@ -60547,8 +60946,10 @@ var ts; return result; function reportErrorResults(source, target, result, isComparingJsxAttributes) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; var maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -60595,7 +60996,7 @@ var ts; if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { var sourceUnionOrIntersection = source; var targetUnionOrIntersection = target; - if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144 /* PrimitiveUnion */) { + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536 /* PrimitiveUnion */) { // There's a fast path for comparing primitive unions return; } @@ -60620,11 +61021,11 @@ var ts; } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & 3145728 /* UnionOrIntersection */) { - var result_6 = eachTypeRelatedToSomeType(source, target); - if (result_6) { - result_6 &= eachTypeRelatedToSomeType(target, source); + var result_7 = eachTypeRelatedToSomeType(source, target); + if (result_7) { + result_7 &= eachTypeRelatedToSomeType(target, source); } - return result_6; + return result_7; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -60639,10 +61040,10 @@ var ts; } function hasExcessProperties(source, target, reportErrors) { var _a; - if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; @@ -61056,21 +61457,21 @@ var ts; if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_7 = 0 /* False */; + var result_8 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_8; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_8; } } } @@ -61150,6 +61551,20 @@ var ts; } } else if (target.flags & 8388608 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { + // Relate components directly before falling back to constraint relationships + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } // A type S is related to a type T[K] if S is related to C, where C is the base // constraint of T[K] for writing. if (relation === assignableRelation || relation === comparableRelation) { @@ -61160,11 +61575,24 @@ var ts; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0); var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + // create a new chain for the constraint error + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { // A source type T is related to a target type { [P in X]: T[P] } @@ -61242,23 +61670,14 @@ var ts; // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - var result_8 = inferTypesFromTemplateLiteralType(source, target); - if (result_8 && ts.every(result_8, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + var result_9 = inferTypesFromTemplateLiteralType(source, target); + if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { return -1 /* True */; } } if (source.flags & 8650752 /* TypeVariable */) { - if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { - // A type S[K] is related to a type T[J] if S is related to T and K is related to J. - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - result &= isRelatedTo(source.indexType, target.indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - else { + // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch + if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) { var constraint = getConstraintOfType(source); if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. @@ -61273,7 +61692,7 @@ var ts; 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, reportErrors, /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -61285,6 +61704,16 @@ var ts; return result; } } + else if (source.flags & 134217728 /* TemplateLiteral */) { + if (!(target.flags & 134217728 /* TemplateLiteral */)) { + var baseConstraint = getBaseConstraintOfType(source); + var constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; + } + } + } else if (source.flags & 268435456 /* StringMapping */) { if (target.flags & 268435456 /* StringMapping */ && source.symbol === target.symbol) { if (result = isRelatedTo(source.type, target.type, reportErrors)) { @@ -61311,7 +61740,7 @@ var ts; if (sourceParams) { // If the source has infer type parameters, we instantiate them in the context of the target var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } @@ -61369,7 +61798,7 @@ var ts; return 0 /* False */; } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && - !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + !(ts.getObjectFlags(source) & 4096 /* MarkerType */ || ts.getObjectFlags(target) & 4096 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. @@ -61397,7 +61826,7 @@ var ts; } // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})` // and not `{} <- fresh({}) <- {[idx: string]: any}` - else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) { + else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 /* FreshLiteral */ && !isEmptyObjectType(source)) { return 0 /* False */; } // Even if relationship doesn't hold for unions, intersections, or generic type references, @@ -61435,14 +61864,19 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_9) { - return result_9; + var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_10) { + return result_10; } } } } return 0 /* False */; + function countMessageChainBreadth(info) { + if (!info) + return 0; + return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0); + } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -61504,13 +61938,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_10; + var result_11; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } } @@ -61650,7 +62084,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_11 = unionParent ? 0 /* False */ : -1 /* True */; + var result_12 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -61660,7 +62094,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_11 &= related; + result_12 &= related; } else { if (related) { @@ -61668,17 +62102,17 @@ var ts; } } } - if (unionParent && !result_11 && targetIsOptional) { - result_11 = isRelatedTo(source, undefinedType); + if (unionParent && !result_12 && targetIsOptional) { + result_12 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_11 && reportErrors) { + if (unionParent && !result_12 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_11; + return result_12; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); @@ -62280,7 +62714,7 @@ var ts; // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); - result.objectFlags |= 8192 /* MarkerType */; + result.objectFlags |= 4096 /* MarkerType */; return result; } function getAliasVariances(symbol) { @@ -62454,8 +62888,8 @@ var ts; } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. - function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons @@ -62473,23 +62907,26 @@ var ts; function isDeeplyNestedType(type, stack, depth) { if (depth >= 5) { var identity_1 = getRecursionIdentity(type); - if (identity_1) { - var count = 0; - for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= 5) { - return true; - } + var count = 0; + for (var i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity_1) { + count++; + if (count >= 5) { + return true; } } } } return false; } - // Types with constituents that could circularly reference the type have a recursion identity. The recursion - // identity is some object that is common to instantiations of the type with the same origin. + // The recursion identity of a type is an object identity that is shared among multiple instantiations of the type. + // We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with + // the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all + // instantiations of that type have the same recursion identity. The default recursion identity is the object + // identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly + // reference the type have a recursion identity that differs from the object identity. function getRecursionIdentity(type) { + // Object and array literals are known not to contain recursive references and don't need a recursion identity. if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) { // Deferred type references are tracked through their associated AST node. This gives us finer @@ -62507,6 +62944,9 @@ var ts; return type.target; } } + if (type.flags & 262144 /* TypeParameter */) { + return type.symbol; + } if (type.flags & 8388608 /* IndexedAccess */) { // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A do { @@ -62518,7 +62958,7 @@ var ts; // The root object represents the origin of the conditional type return type.root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; @@ -62656,6 +63096,9 @@ var ts; // 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; }); @@ -62688,12 +63131,30 @@ var ts; function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return isArrayType(type) || hasArrayOrReadonlyArrayBaseType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } - function hasArrayOrReadonlyArrayBaseType(type) { - return !!(ts.getObjectFlags(type) & 4 /* Reference */) - && !!(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */) - && ts.some(getBaseTypes(type.target), isArrayType); + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */)) { + return undefined; + } + if (ts.getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) { + return ts.getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : undefined; + } + type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */; + var target = type.target; + var bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; // If the interface has any members, they may subtype members in the base, so we should do a full structural comparison + } + var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type))); + } + type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */; + return type.cachedEquivalentBaseType = instantiatedBase; } function isEmptyArrayLiteralType(type) { var elementType = getElementTypeOfArrayType(type); @@ -62938,7 +63399,7 @@ var ts; function isObjectTypeWithInferableIndex(type) { return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */); @@ -62971,7 +63432,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -62982,7 +63443,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */; + regularNew.objectFlags |= resolved.objectFlags & ~16384 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -63012,7 +63473,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; - if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304 /* ContainsSpread */)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; names.set(prop.escapedName, prop); @@ -63061,14 +63522,14 @@ var ts; var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (8192 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -63113,7 +63574,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -63139,7 +63600,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -63219,7 +63680,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -63335,16 +63796,16 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) { - return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); + if (objectFlags & 1048576 /* CouldContainTypeVariablesComputed */) { + return !!(objectFlags & 2097152 /* CouldContainTypeVariables */); } var result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 8388608 /* ObjectRestType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { - type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); + type.objectFlags |= 1048576 /* CouldContainTypeVariablesComputed */ | (result ? 2097152 /* CouldContainTypeVariables */ : 0); } return result; } @@ -63404,7 +63865,7 @@ var ts; // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive // arrow function, but is considered partially inferable because property 'a' has an inferable type. function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 524288 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) || isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType); } @@ -63428,14 +63889,18 @@ var ts; } // For all other object types we infer a new object type where the reverse mapping has been // applied to the type of each property. - var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + var reversed = createObjectType(1024 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType, target, constraint) { var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); @@ -63633,7 +64098,7 @@ var ts; if (contravariant === void 0) { contravariant = false; } var bivariant = false; var propagationType; - var inferencePriority = 1024 /* MaxValue */; + var inferencePriority = 2048 /* MaxValue */; var allowComplexConstraintInference = true; var visited; var sourceStack; @@ -63720,8 +64185,8 @@ var ts; // 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 (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || - (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || + (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -63748,7 +64213,7 @@ var ts; clearCachedInferences(inferences); } } - if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -63788,7 +64253,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - inferWithPriority(empty, target.type, 128 /* LiteralKeyof */); + inferWithPriority(empty, target.type, 256 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -63800,6 +64265,13 @@ var ts; inferFromTypes(source.type, target.type); } } + else if (source.flags & 33554432 /* Substitution */) { + inferFromTypes(source.baseType, target); + var oldPriority = priority; + priority |= 4 /* SubstituteSource */; + inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority + priority = oldPriority; + } else if (target.flags & 16777216 /* Conditional */) { invokeOnce(source, target, inferToConditionalType); } @@ -63819,7 +64291,7 @@ var ts; } else { source = getReducedType(source); - if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { + if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` @@ -63857,26 +64329,22 @@ var ts; } (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */); var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; // We stop inferring and report a circularity if we encounter duplicate recursion identities on both // the source side and the target side. var saveExpandingFlags = expandingFlags; - var sourceIdentity = getRecursionIdentity(source) || source; - var targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && ts.contains(sourceStack, sourceIdentity)) + var sourceIdentity = getRecursionIdentity(source); + var targetIdentity = getRecursionIdentity(target); + if (ts.contains(sourceStack, sourceIdentity)) expandingFlags |= 1 /* Source */; - if (targetIdentity && ts.contains(targetStack, targetIdentity)) + if (ts.contains(targetStack, targetIdentity)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { - if (sourceIdentity) - (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) - (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) - targetStack.pop(); - if (sourceIdentity) - sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = -1 /* Circularity */; @@ -63916,7 +64384,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -63968,7 +64436,7 @@ var ts; else { for (var i = 0; i < sources.length; i++) { var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; inferFromTypes(sources[i], t); if (inferencePriority === priority) matched_1[i] = true; @@ -64047,7 +64515,7 @@ var ts; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? 8 /* PartialHomomorphicMappedType */ : 4 /* HomomorphicMappedType */); + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 /* NonInferrableType */ ? 16 /* PartialHomomorphicMappedType */ : 8 /* HomomorphicMappedType */); } } return true; @@ -64055,7 +64523,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */); + inferWithPriority(getIndexType(source), constraintType, 32 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -64084,7 +64552,7 @@ var ts; } else { var savePriority = priority; - priority |= contravariant ? 32 /* ContravariantConditional */ : 0; + priority |= contravariant ? 64 /* ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, target.flags); priority = savePriority; @@ -64207,7 +64675,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -64258,7 +64726,7 @@ var ts; return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); } function isObjectOrArrayLiteralType(type) { - return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */)); + return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 32768 /* ArrayLiteral */)); } function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { @@ -64271,7 +64739,7 @@ var ts; return candidates; } function getContravariantInference(inference) { - return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } function getCovariantInference(inference, signature) { // Extract all object and array literal types and replace them with a single widened and normalized type. @@ -64288,7 +64756,7 @@ var ts; candidates; // If all inferences were made from a position that implies a combined result, infer a union type. // Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ? + var unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -64585,14 +65053,14 @@ var ts; function getKeyPropertyName(unionType) { var types = unionType.types; // We only construct maps for large unions with non-primitive constituents. - if (types.length < 10 || ts.getObjectFlags(unionType) & 262144 /* PrimitiveUnion */) { + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { return undefined; } if (unionType.keyPropertyName === undefined) { // The candidate key property name is the name of the first property with a unit type in one of the // constituent types. var keyPropertyName = ts.forEach(types, function (t) { - return t.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? + return t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) : undefined; }); @@ -64687,7 +65155,8 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, ignoreObjects) { + if (ignoreObjects === void 0) { ignoreObjects = false; } var flags = type.flags; if (flags & 4 /* String */) { return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; @@ -64724,7 +65193,7 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 524288 /* Object */) { + if (flags & 524288 /* Object */ && !ignoreObjects) { return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? @@ -64747,14 +65216,17 @@ var ts; return 0 /* None */; } if (flags & 465829888 /* Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */; } if (flags & 1048576 /* Union */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t); }, 0 /* None */); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* None */); } if (flags & 2097152 /* Intersection */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t); }, 16777215 /* All */); + // 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 /* Primitive */)); + return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */); } return 16777215 /* All */; } @@ -64963,6 +65435,9 @@ var ts; function everyType(type, f) { return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } + function everyContainedType(type, f) { + return type.flags & 3145728 /* UnionOrIntersection */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 1048576 /* Union */) { var types = type.types; @@ -66263,7 +66738,16 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); + return filterType(type, function (t) { + if (!isRelated(t, candidate)) { + return true; + } + var constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } // 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. @@ -66358,17 +66842,20 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 78 /* Identifier */) { + if (location.kind === 78 /* Identifier */ || location.kind === 79 /* PrivateIdentifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true); + } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the @@ -66493,7 +66980,6 @@ var ts; } } function checkIdentifier(node, checkMode) { - var _a; var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -66595,7 +67081,7 @@ var ts; } } else if (isAlias) { - declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -66808,7 +67294,7 @@ var ts; break; case 164 /* PropertyDeclaration */: case 163 /* PropertySignature */: - if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } @@ -67451,16 +67937,16 @@ var ts; // In an assignment expression, the right operand is contextually typed by the type of the left operand. // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return getTypeOfExpression(binaryExpression.left); + case 4 /* ThisProperty */: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case 5 /* Property */: - case 1 /* ExportsProperty */: - case 6 /* Prototype */: - case 3 /* PrototypeProperty */: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. @@ -67481,11 +67967,11 @@ var ts; var id = lhs.expression; var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true); if (parentSymbol) { - var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); - if (annotated) { + var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated_1) { var nameStr = ts.getElementOrPropertyAccessName(lhs); if (nameStr !== undefined) { - return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr); + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr); } } return undefined; @@ -67493,9 +67979,15 @@ var ts; } return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; + // falls through case 2 /* ModuleExports */: - case 4 /* ThisProperty */: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); + var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case 7 /* ObjectDefinePropertyValue */: case 8 /* ObjectDefinePropertyExports */: case 9 /* ObjectDefinePrototypeProperty */: @@ -67516,7 +68008,7 @@ var ts; var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true); return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) { + function getContextualTypeForThisPropertyAssignment(binaryExpression) { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { @@ -67528,8 +68020,6 @@ var ts; } } } - if (kind === 2 /* ModuleExports */) - return undefined; var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression); if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return undefined; @@ -67584,6 +68074,10 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { if (hasBindableName(element)) { @@ -67681,10 +68175,10 @@ var ts; return false; } function discriminateContextualTypeByObjectMembers(node, contextualType) { - return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -67793,7 +68287,7 @@ var ts; case 290 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent, contextFlags); case 291 /* SpreadAssignment */: - return getApparentTypeOfContextualType(parent.parent, contextFlags); + return getContextualType(parent.parent, contextFlags); case 200 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); @@ -68189,7 +68683,7 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 32768 /* ArrayLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; } return literalType; } @@ -68346,7 +68840,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -68474,9 +68968,9 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { - result.objectFlags |= 16384 /* JSLiteral */; + result.objectFlags |= 8192 /* JSLiteral */; } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -68566,14 +69060,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var objectFlags = 4096 /* JsxAttributes */; + var objectFlags = 2048 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -68657,7 +69151,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -69159,7 +69653,7 @@ var ts; // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { @@ -69334,6 +69828,23 @@ var ts; if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); } + if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (compilerOptions.target === 99 /* ESNext */ && !useDefineForClassFields)) { + var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); + var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { + if (n === lexicalClass_1) + return "quit"; + if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); + } + } if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -69423,7 +69934,10 @@ var ts; // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + prop && + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) + && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { @@ -69466,6 +69980,7 @@ var ts; var diagnosticMessage; var declarationName = ts.idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { @@ -69571,7 +70086,10 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + var diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : ts.Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -69582,6 +70100,11 @@ var ts; } diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) && + isEmptyObjectType(containingType); + } function typeHasStaticProperty(propName, containingType) { var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); return prop !== undefined && !!prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); @@ -70048,7 +70571,7 @@ var ts; }); if (!inferenceContext) { applyToReturnTypes(contextualSignature, signature, function (source, target) { - inferTypes(context.inferences, source, target, 64 /* ReturnType */); + inferTypes(context.inferences, source, target, 128 /* ReturnType */); }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); @@ -70098,7 +70621,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* 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 @@ -70543,77 +71066,66 @@ var ts; return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - var belowArgCount = Number.NEGATIVE_INFINITY; - var aboveArgCount = Number.POSITIVE_INFINITY; - var argCount = args.length; + var _a; + var spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } + var min = Number.POSITIVE_INFINITY; // smallest parameter count + var max = Number.NEGATIVE_INFINITY; // largest parameter count + var maxBelow = Number.NEGATIVE_INFINITY; // largest parameter count that is smaller than the number of arguments + var minAbove = Number.POSITIVE_INFINITY; // smallest parameter count that is larger than the number of arguments var closestSignature; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var sig = signatures_8[_i]; - var minCount = getMinArgumentCount(sig); - var maxCount = getParameterCount(sig); - if (minCount < argCount && minCount > belowArgCount) - belowArgCount = minCount; - if (argCount < maxCount && maxCount < aboveArgCount) - aboveArgCount = maxCount; - if (minCount < min) { - min = minCount; + var minParameter = getMinArgumentCount(sig); + var maxParameter = getParameterCount(sig); + // smallest/largest parameter counts + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + max = Math.max(max, maxParameter); + // shortest parameter count *longer than the call*/longest parameter count *shorter than the call* + if (minParameter < args.length && minParameter > maxBelow) + maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) + minAbove = maxParameter; } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); - var paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var spanArray; - var related; - var error = hasRestParameter || hasSpreadArgument ? - hasRestParameter && hasSpreadArgument ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - ts.Diagnostics.Expected_0_arguments_but_got_1; - if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { - var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; - if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : - ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); - } - } - if (!hasSpreadArgument && argCount < min) { - var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } - if (hasRestParameter || hasSpreadArgument) { - spanArray = ts.factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); + var parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : ts.Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + // between min and max, but with no matching overload + return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + // too short: put the error span on the call expression, not any of the args + var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined); + return ts.addRelatedInfo(diagnostic, parameterError); } + return diagnostic; } else { - spanArray = ts.factory.createNodeArray(args.slice(max)); - } - var pos = ts.first(spanArray).pos; - var end = ts.last(spanArray).end; - if (end === pos) { - end++; + // too long; error goes on the excess parameters + var errorSpan = ts.factory.createNodeArray(args.slice(max)); + var pos = ts.first(errorSpan).pos; + var end = ts.last(errorSpan).end; + if (end === pos) { + end++; + } + ts.setTextRangePosEnd(errorSpan, pos, end); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - ts.setTextRangePosEnd(spanArray, pos, end); - var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -71706,7 +72218,7 @@ var ts; var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false); if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) { var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + jsAssignmentType.objectFlags |= 8192 /* JSLiteral */; return getIntersectionType([returnType, jsAssignmentType]); } } @@ -72138,7 +72650,14 @@ var ts; } } function assignContextualParameterTypes(signature, context) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; // This signature has already has a contextual inference performed and cached on it! + } + } if (context.thisParameter) { var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { @@ -72531,17 +73050,17 @@ var ts; return; } var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */; + var errorNode = ts.getEffectiveReturnTypeNode(func) || func; if (type && type.flags & 131072 /* Never */) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { // minimal check: function has syntactic return type annotation and no explicit return statements in the body // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -72556,7 +73075,7 @@ var ts; return; } } - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { @@ -72576,7 +73095,7 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; + returnOnlyType.objectFlags |= 524288 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } } @@ -74377,7 +74896,7 @@ var ts; checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { if (!(func.kind === 167 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } @@ -74834,9 +75353,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); })); + ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -74888,15 +75407,18 @@ var ts; var symbol = getSymbolOfNode(node); var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); - if (getter && setter) { + if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) { + getNodeLinks(getter).flags |= 1 /* TypeChecked */; var getterFlags = ts.getEffectiveModifierFlags(getter); var setterFlags = ts.getEffectiveModifierFlags(setter); if ((getterFlags & 128 /* Abstract */) !== (setterFlags & 128 /* Abstract */)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } if (((getterFlags & 16 /* Protected */) && !(setterFlags & (16 /* Protected */ | 8 /* Private */))) || ((getterFlags & 8 /* Private */) && !(setterFlags & 8 /* Private */))) { - error(node.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } var getterType = getAnnotatedAccessorType(getter); var setterType = getAnnotatedAccessorType(setter); @@ -75456,20 +75978,23 @@ var ts; case 298 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: + var node_2 = d; + var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values - if (!ts.isEntityNameExpression(d.expression)) { + if (!ts.isEntityNameExpression(expression)) { return 1 /* ExportValue */; } - d = d.expression; + d = expression; // The below options all declare an Alias, which is allowed to merge with other values within the importing module. // falls through case 261 /* ImportEqualsDeclaration */: case 264 /* NamespaceImport */: case 263 /* ImportClause */: - var result_12 = 0 /* None */; + var result_13 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); - return result_12; + ts.forEach(target.declarations, function (d) { result_13 |= getDeclarationSpaces(d); }); + return result_13; case 250 /* VariableDeclaration */: case 199 /* BindingElement */: case 252 /* FunctionDeclaration */: @@ -76790,11 +77315,6 @@ var ts; return; if (getFalsyFlags(type)) return; - if (getAwaitedTypeOfPromise(type)) { - errorAndMaybeSuggestAwait(condExpr, - /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined, getTypeNameForErrorDisplay(type)); - return; - } var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr; var testedNode = ts.isIdentifier(location) ? location : ts.isPropertyAccessExpression(location) ? location.name @@ -76806,25 +77326,32 @@ var ts; return; } // While it technically should be invalid for any known-truthy value - // to be tested, we de-scope to functions unrefenced in the block as a - // heuristic to identify the most common bugs. There are too many - // false positives for values sourced from type definitions without - // strictNullChecks otherwise. + // to be tested, we de-scope to functions and Promises unreferenced in + // the block as a heuristic to identify the most common bugs. There + // are too many false positives for values sourced from type + // definitions without strictNullChecks otherwise. var callSignatures = getSignaturesOfType(type, 0 /* Call */); - if (callSignatures.length === 0) { + var isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } var testedSymbol = getSymbolAtLocation(testedNode); if (!testedSymbol) { return; } - var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + var isUsed = ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait(location, + /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); + } + else { + error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) { + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { return !!ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); @@ -76861,7 +77388,7 @@ var ts; return ts.forEachChild(childNode, check); }); } - function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) { + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { var isUsed = ts.forEachChild(node.right, function visit(child) { if (ts.isIdentifier(child)) { @@ -78184,7 +78711,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - checkMembersForMissingOverrideModifier(node, type, typeWithThis); + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -78219,12 +78746,16 @@ var ts; checkPropertyInitialization(node); } } - function checkMembersForMissingOverrideModifier(node, type, typeWithThis) { + function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); var baseTypeNode = ts.getEffectiveBaseTypeNode(node); var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); var _loop_24 = function (member) { + if (ts.hasAmbientModifier(member)) { + return "continue"; + } if (ts.isConstructorDeclaration(member)) { ts.forEach(member.parameters, function (param) { if (ts.isParameterPropertyDeclaration(param, member)) { @@ -78240,14 +78771,17 @@ var ts; } function checkClassMember(member, memberIsParameterProperty) { var hasOverride = ts.hasOverrideModifier(member); + var hasStatic = ts.hasStaticModifier(member); if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); if (!declaredProp) { return; } + var thisType = hasStatic ? staticType : typeWithThis; + var baseType = hasStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); var baseClassName = typeToString(baseWithThis); - var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); - var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && !baseProp && hasOverride) { error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } @@ -78258,7 +78792,7 @@ var ts; } if (!baseHasAbstract) { var diag = memberIsParameterProperty ? - ts.Diagnostics.This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; error(member, diag, baseClassName); } @@ -78412,7 +78946,7 @@ var ts; ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { + else if (useDefineForClassFields) { var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 164 /* PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* Transient */) @@ -79288,7 +79822,10 @@ var ts; } } function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + var illegalContextMessage = node.isExportEquals + ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } @@ -79377,10 +79914,12 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, _b = declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (var _i = 0, _b = declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } } @@ -79389,6 +79928,11 @@ var ts; links.exportsChecked = true; } } + function isDuplicatedCommonJSExport(declarations) { + return declarations + && declarations.length > 1 + && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); }); + } function checkSourceElement(node) { if (node) { var saveCurrentNode = currentNode; @@ -79619,7 +80163,8 @@ var ts; if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_1) { + var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent); + if (host_1 || isCallbackTag) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -79627,7 +80172,9 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var lastParamDeclaration = isCallbackTag + ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) + : ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -79843,11 +80390,11 @@ var ts; } switch (location.kind) { case 298 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) + if (!ts.isExternalModule(location)) break; // falls through case 257 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; case 256 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); @@ -79910,6 +80457,16 @@ var ts; }); } } + function copyLocallyVisibleExportSymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + // Similar condition as in `resolveNameHelper` + if (!ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 270 /* NamespaceExport */)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name) { return name.kind === 78 /* Identifier */ && @@ -79949,14 +80506,14 @@ var ts; } return node.parent.kind === 224 /* ExpressionWithTypeArguments */; } - function isJSDocEntryNameReference(node) { + function getJSDocEntryNameReference(node) { while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 303 /* JSDocNameReference */; + return ts.isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node, callback) { var result; @@ -80118,18 +80675,34 @@ var ts; var meaning = name.parent.kind === 174 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (isJSDocEntryNameReference(name)) { - var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); - } - else if (ts.isJSDocLink(name.parent)) { + var jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || ts.isJSDocLink(name.parent)) { var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ true); + var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ false, ts.getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (ts.isQualifiedName(name) && ts.isIdentifier(name.left)) { + // resolve C.m as a static member first + var links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, 0 /* Normal */); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + // then resolve it as an instance member + var s = resolveEntityName(name.left, meaning, /*ignoreErrors*/ false); + if (s) { + var t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } } if (name.parent.kind === 173 /* TypePredicate */) { return resolveEntityName(name, 1 /* FunctionScopedVariable */); } - // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node, ignoreErrors) { @@ -80329,10 +80902,10 @@ var ts; // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { if (expr.parent.kind === 289 /* PropertyAssignment */) { - var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); - var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType; - var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent); - return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex); + var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); + var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; + var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex); } // Array literal assignment - array destructuring pattern var node = ts.cast(expr.parent, ts.isArrayLiteralExpression); @@ -80686,13 +81259,13 @@ var ts; !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && !!parameter.initializer && - !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + !ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameter(parameter) { return !!strictNullChecks && @@ -81400,17 +81973,18 @@ var ts; } break; case 156 /* OverrideKeyword */: + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override"); } else if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); } - else if (flags & 32 /* Static */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "override"); + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); } - if (node.kind === 161 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "override"); + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); } flags |= 16384 /* Override */; lastOverride = modifier; @@ -81422,7 +81996,7 @@ var ts; if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + else if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); } else if (flags & 32 /* Static */) { @@ -81457,9 +82031,6 @@ var ts; else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "override"); - } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } @@ -81472,6 +82043,9 @@ var ts; else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); + } flags |= 32 /* Static */; lastStatic = modifier; break; @@ -81480,7 +82054,7 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } else if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */ && node.kind !== 172 /* IndexSignature */ && node.kind !== 161 /* Parameter */) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; @@ -81521,7 +82095,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + else if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); } else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { @@ -81563,6 +82137,9 @@ var ts; if (flags & 256 /* Async */ && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -81594,7 +82171,7 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } - if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + if (flags & 16384 /* Override */) { return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 } else if (flags & 256 /* Async */) { @@ -81608,10 +82185,10 @@ var ts; else if ((node.kind === 262 /* ImportDeclaration */ || node.kind === 261 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 161 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 161 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -82895,20 +83472,6 @@ var ts; return ts.isDeclarationName(name); } } - function isSomeImportDeclaration(decl) { - switch (decl.kind) { - case 263 /* ImportClause */: // For default import - case 261 /* ImportEqualsDeclaration */: - case 264 /* NamespaceImport */: - case 266 /* ImportSpecifier */: - return true; - case 78 /* Identifier */: - // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 266 /* ImportSpecifier */; - default: - return false; - } - } var JsxNames; (function (JsxNames) { JsxNames.JSX = "JSX"; @@ -87778,10 +88341,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_1 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_1, node); - ts.setCommentRange(clone_1, node); - return clone_1; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -87866,6 +88429,7 @@ var ts; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var shouldTransformPrivateElements = languageVersion < 99 /* ESNext */; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; @@ -87887,7 +88451,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === 99 /* ESNext */) { + || useDefineForClassFields && options.target === 99 /* ESNext */) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -88046,7 +88610,7 @@ var ts; // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } @@ -88357,7 +88921,7 @@ var ts; if (ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. return languageVersion < 99 /* ESNext */; @@ -88380,7 +88944,6 @@ var ts; /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); @@ -88492,7 +89055,7 @@ var ts; function transformProperty(property, receiver) { var _a; // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) - var emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + var emitAssignment = !useDefineForClassFields; var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; @@ -88597,10 +89160,10 @@ var ts; 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; + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; } } } @@ -90762,9 +91325,9 @@ var ts; function convertJsxChildrenToChildrenPropObject(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) + var result_14 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_14 && factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("children", result_14) ]); } var result = ts.mapDefined(children, transformJsxChildToExpression); @@ -92496,7 +93059,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName); var e; - if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) { var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; @@ -93319,13 +93882,13 @@ var ts; loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); - loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); + loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { - var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; @@ -96271,10 +96834,10 @@ var ts; var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { // TODO(rbuckton): Does this need to be parented? - var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); - ts.setSourceMapRange(clone_5, node); - ts.setCommentRange(clone_5, node); - return clone_5; + var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -97268,8 +97831,6 @@ var ts; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(204 /* CallExpression */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(206 /* TaggedTemplateExpression */); // Substitutes expression identifiers with imported/exported symbols. context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. @@ -97280,7 +97841,6 @@ var ts; var currentModuleInfo; // The ExternalModuleInfo for the current file. var noSubstitution; // Set of nodes for which substitution rules should be ignored. var needUMDDynamicImportHelper; - var bindingReferenceCache; return ts.chainBundle(context, transformSourceFile); /** * Transforms the module aspects of a SourceFile. @@ -98527,10 +99087,6 @@ var ts; return substituteExpressionIdentifier(node); case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 204 /* CallExpression */: - return substituteCallExpression(node); - case 206 /* TaggedTemplateExpression */: - return substituteTaggedTemplateExpression(node); case 216 /* PostfixUnaryExpression */: case 215 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); @@ -98538,99 +99094,41 @@ var ts; return node; } /** - * For an Identifier, gets the import or export binding that it references. - * @returns One of the following: - * - An `Identifier` if node references an external helpers module (i.e., `tslib`). - * - A `SourceFile` if the node references an export in the file. - * - An `ImportClause` or `ImportSpecifier` if the node references an import binding. - * - Otherwise, `undefined`. + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. */ - function getImportOrExportBindingReferenceWorker(node) { + function substituteExpressionIdentifier(node) { + var _a, _b; if (ts.getEmitFlags(node) & 4096 /* HelperName */) { var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); if (externalHelpersModuleName) { - return externalHelpersModuleName; + return factory.createPropertyAccessExpression(externalHelpersModuleName, node); } + return node; } else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if ((exportContainer === null || exportContainer === void 0 ? void 0 : exportContainer.kind) === 298 /* SourceFile */) { - return exportContainer; + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { + return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), + /*location*/ node); } var importDeclaration = resolver.getReferencedImportDeclaration(node); - if (importDeclaration && (ts.isImportClause(importDeclaration) || ts.isImportSpecifier(importDeclaration))) { - return importDeclaration; - } - } - return undefined; - } - /** - * For an Identifier, gets the import or export binding that it references. - * @param removeEntry When `false`, the result is cached to avoid recomputing the result in a later substitution. - * When `true`, any cached result for the node is removed. - * @returns One of the following: - * - An `Identifier` if node references an external helpers module (i.e., `tslib`). - * - A `SourceFile` if the node references an export in the file. - * - An `ImportClause` or `ImportSpecifier` if the node references an import binding. - * - Otherwise, `undefined`. - */ - function getImportOrExportBindingReference(node, removeEntry) { - var result = bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.get(node); - if (!result && !(bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.has(node))) { - result = getImportOrExportBindingReferenceWorker(node); - if (!removeEntry) { - bindingReferenceCache || (bindingReferenceCache = new ts.Map()); - bindingReferenceCache.set(node, result); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || importDeclaration), factory.cloneNode(name)), + /*location*/ node); + } } } - else if (removeEntry) { - bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.delete(node); - } - return result; - } - function substituteCallExpression(node) { - if (ts.isIdentifier(node.expression) && getImportOrExportBindingReference(node.expression, /*removeEntry*/ false)) { - return ts.isCallChain(node) ? - factory.updateCallChain(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.expression), node.expression), node.questionDotToken, - /*typeArguments*/ undefined, node.arguments) : - factory.updateCallExpression(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.expression), node.expression), - /*typeArguments*/ undefined, node.arguments); - } - return node; - } - function substituteTaggedTemplateExpression(node) { - if (ts.isIdentifier(node.tag) && getImportOrExportBindingReference(node.tag, /*removeEntry*/ false)) { - return factory.updateTaggedTemplateExpression(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.tag), node.tag), - /*typeArguments*/ undefined, node.template); - } return node; } - /** - * Substitution for an Identifier expression that may contain an imported or exported - * symbol. - * - * @param node The node to substitute. - */ - function substituteExpressionIdentifier(node) { - var _a, _b; - var result = getImportOrExportBindingReference(node, /*removeEntry*/ true); - switch (result === null || result === void 0 ? void 0 : result.kind) { - case 78 /* Identifier */: - return factory.createPropertyAccessExpression(result, node); - case 298 /* SourceFile */: - return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), - /*location*/ node); - case 263 /* ImportClause */: - return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(result.parent), factory.createIdentifier("default")), - /*location*/ node); - case 266 /* ImportSpecifier */: - var name = result.propertyName || result.name; - return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = result.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || result), factory.cloneNode(name)), - /*location*/ node); - default: - return node; - } - } /** * Substitution for a BinaryExpression that may contain an imported or exported symbol. * @@ -99892,7 +100390,7 @@ var ts; return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } /** - * Determines whether the target of a destructuring assigment refers to an exported symbol. + * Determines whether the target of a destructuring assignment refers to an exported symbol. * * @param node The destructuring target. */ @@ -101076,7 +101574,7 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, + var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, /*preferences*/ undefined); if (!ts.pathIsRelative(specifier)) { // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration @@ -101822,7 +102320,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param)) + if (!ts.hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 78 /* Identifier */) { @@ -102607,32 +103105,32 @@ var ts; } ts.transformNodes = transformNodes; ts.nullTransformationContext = { - get factory() { return ts.factory; }, - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: ts.returnUndefined, + factory: ts.factory, getCompilerOptions: function () { return ({}); }, - getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + getEmitHost: ts.notImplemented, getEmitHelperFactory: ts.notImplemented, + startLexicalEnvironment: ts.noop, + resumeLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + endLexicalEnvironment: ts.returnUndefined, setLexicalEnvironmentFlags: ts.noop, getLexicalEnvironmentFlags: function () { return 0; }, - hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + hoistFunctionDeclaration: ts.noop, addInitializationStatement: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop, - addDiagnostic: ts.noop, startBlockScope: ts.noop, endBlockScope: ts.returnUndefined, - addBlockScopedVariable: ts.noop + addBlockScopedVariable: ts.noop, + requestEmitHelper: ts.noop, + readEmitHelpers: ts.notImplemented, + enableSubstitution: ts.noop, + enableEmitNotification: ts.noop, + isSubstitutionEnabled: ts.notImplemented, + isEmitNotificationEnabled: ts.notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, + addDiagnostic: ts.noop, }; })(ts || (ts = {})); var ts; @@ -103381,10 +103879,18 @@ var ts; return outputFiles; } ts.emitUsingBuildInfo = emitUsingBuildInfo; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); var moduleKind = ts.getEmitModuleKind(printerOptions); @@ -103423,8 +103929,10 @@ var ts; var detachedCommentsInfo; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; - var _a = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _a.enter, exitComment = _a.exit; - var preprint = createPreprinter(handlers); + var lastSubstitution; + var currentParenthesizerRule; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + var parenthesizer = ts.factory.parenthesizer; var emitBinaryExpression = createEmitBinaryExpression(); reset(); return { @@ -103624,7 +104132,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - emit(preprint(hint, node)); + pipelineEmit(hint, node, /*parenthesizerRule*/ undefined); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -103657,13 +104165,40 @@ var ts; function getCurrentLineMap() { return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } - function emit(node) { + function emit(node, parenthesizerRule) { if (node === undefined) return; var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - emitWithContext(node, emitWorker); + pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); } + function emitIdentifierName(node) { + if (node === undefined) + return; + pipelineEmit(2 /* IdentifierName */, node, /*parenthesizerRule*/ undefined); + } + function emitExpression(node, parenthesizerRule) { + if (node === undefined) + return; + pipelineEmit(1 /* Expression */, node, parenthesizerRule); + } + function emitJsxAttributeValue(node) { + pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); + } + function beforeEmitNode(node) { + if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { + preserveSourceNewlines = false; + } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; + var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); + pipelinePhase(emitHint, node); + currentParenthesizerRule = undefined; + } function shouldEmitComments(node) { return !commentsDisabled && !ts.isSourceFile(node); } @@ -103674,484 +104209,504 @@ var ts; !ts.isUnparsedSource(node) && !ts.isUnparsedPrepend(node); } - function beforeEmitWithContext(node, shouldEmitComments, shouldEmitSourceMaps) { - onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); - var emitFlags = ts.getEmitFlags(node); - var commentRange = shouldEmitComments ? ts.getCommentRange(node) : undefined; - var sourceMapRange = shouldEmitSourceMaps ? ts.getSourceMapRange(node) : undefined; - if (preserveSourceNewlines && (emitFlags & 134217728 /* IgnoreSourceNewlines */)) { - preserveSourceNewlines = false; - } - // Emit leading comments - if (commentRange) { - emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = true; - } - } - // Emit leading sourcemap - if (sourceMapRange) { - if (ts.isUnparsedNode(node)) { - ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); - var parsed = getParsedSourceMap(node.parent); - if (parsed && sourceMapGenerator) { - sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); + function getPipelinePhase(phase, emitHint, node) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { + return pipelineEmitWithNotification; } - } - else { - var source = sourceMapRange.source || sourceMapSource; - if (node.kind !== 339 /* NotEmittedStatement */ - && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && sourceMapRange.pos >= 0) { - emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + // falls through + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } + return pipelineEmitWithSubstitution; } - if (emitFlags & 64 /* NoNestedSourceMaps */) { - sourceMapsDisabled = true; + // falls through + case 2 /* Comments */: + if (shouldEmitComments(node)) { + return pipelineEmitWithComments; } - } + // falls through + case 3 /* SourceMaps */: + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; + } + // falls through + case 4 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase); } } - function afterEmitWithContext(node, shouldEmitComments, shouldEmitSourceMaps, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines) { - var emitFlags = ts.getEmitFlags(node); - var commentRange = shouldEmitComments ? ts.getCommentRange(node) : undefined; - var sourceMapRange = shouldEmitSourceMaps ? ts.getSourceMapRange(node) : undefined; - // Emit trailing sourcemap - if (sourceMapRange) { - if (!ts.isUnparsedNode(node)) { - if (emitFlags & 64 /* NoNestedSourceMaps */) { - sourceMapsDisabled = false; - } - if (node.kind !== 339 /* NotEmittedStatement */ - && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && sourceMapRange.end >= 0) { - emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); - } - } + function getNextPipelinePhase(currentPhase, emitHint, node) { + return getPipelinePhase(currentPhase + 1, emitHint, node); + } + function pipelineEmitWithNotification(hint, node) { + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + var savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); } - // Emit trailing comments - if (commentRange) { - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = false; - } - emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + else { + pipelineEmitWithHintWorker(hint, node); } - preserveSourceNewlines = savedPreserveSourceNewlines; onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + // clear the parenthesizer rule as we ascend + currentParenthesizerRule = undefined; } - function emitWithContext(node, emitCallback) { - var savedPreserveSourceNewlines = preserveSourceNewlines; - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; - var emitComments = shouldEmitComments(node); - var emitSourceMaps = shouldEmitSourceMaps(node); - beforeEmitWithContext(node, emitComments, emitSourceMaps); - emitCallback(node); - afterEmitWithContext(node, emitComments, emitSourceMaps, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines); - } - function emitWorker(node) { - switch (node.kind) { - // Literals - case 8 /* NumericLiteral */: - case 9 /* BigIntLiteral */: - return emitNumericOrBigIntLiteral(node); - case 10 /* StringLiteral */: - case 13 /* RegularExpressionLiteral */: - case 14 /* NoSubstitutionTemplateLiteral */: - return emitLiteral(node, /*jsxAttributeEscape*/ false); - case 11 /* JsxText */: - return emitJsxText(node); - // Pseudo-literals - case 15 /* TemplateHead */: - case 16 /* TemplateMiddle */: - case 17 /* TemplateTail */: - return emitLiteral(node, /*jsxAttributeEscape*/ false); - // Identifiers and PrivateIdentifiers - case 78 /* Identifier */: - return emitIdentifier(node); - case 79 /* PrivateIdentifier */: - return emitPrivateIdentifier(node); - // Names - case 158 /* QualifiedName */: - return emitQualifiedName(node); - case 159 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - // Signature elements - case 160 /* TypeParameter */: - return emitTypeParameter(node); - case 161 /* Parameter */: - return emitParameter(node); - case 162 /* Decorator */: - return emitDecorator(node); - // Type members - case 163 /* PropertySignature */: - return emitPropertySignature(node); - case 164 /* PropertyDeclaration */: - return emitPropertyDeclaration(node); - case 165 /* MethodSignature */: - return emitMethodSignature(node); - case 166 /* MethodDeclaration */: - return emitMethodDeclaration(node); - case 167 /* Constructor */: - return emitConstructor(node); - case 168 /* GetAccessor */: - case 169 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 170 /* CallSignature */: - return emitCallSignature(node); - case 171 /* ConstructSignature */: - return emitConstructSignature(node); - case 172 /* IndexSignature */: - return emitIndexSignature(node); - // Types - case 173 /* TypePredicate */: - return emitTypePredicate(node); - case 174 /* TypeReference */: - return emitTypeReference(node); - case 175 /* FunctionType */: - return emitFunctionType(node); - case 176 /* ConstructorType */: - return emitConstructorType(node); - case 177 /* TypeQuery */: - return emitTypeQuery(node); - case 178 /* TypeLiteral */: - return emitTypeLiteral(node); - case 179 /* ArrayType */: - return emitArrayType(node); - case 180 /* TupleType */: - return emitTupleType(node); - case 181 /* OptionalType */: - return emitOptionalType(node); - // SyntaxKind.RestType is handled below - case 183 /* UnionType */: - return emitUnionType(node); - case 184 /* IntersectionType */: - return emitIntersectionType(node); - case 185 /* ConditionalType */: - return emitConditionalType(node); - case 186 /* InferType */: - return emitInferType(node); - case 187 /* ParenthesizedType */: - return emitParenthesizedType(node); - case 188 /* ThisType */: - return emitThisType(); - case 189 /* TypeOperator */: - return emitTypeOperator(node); - case 190 /* IndexedAccessType */: - return emitIndexedAccessType(node); - case 191 /* MappedType */: - return emitMappedType(node); - case 192 /* LiteralType */: - return emitLiteralType(node); - case 193 /* NamedTupleMember */: - return emitNamedTupleMember(node); - case 194 /* TemplateLiteralType */: - return emitTemplateType(node); - case 195 /* TemplateLiteralTypeSpan */: - return emitTemplateTypeSpan(node); - case 196 /* ImportType */: - return emitImportTypeNode(node); - // Binding patterns - case 197 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 198 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 199 /* BindingElement */: - return emitBindingElement(node); - // Expressions - case 200 /* ArrayLiteralExpression */: - return emitArrayLiteralExpression(node); - case 201 /* ObjectLiteralExpression */: - return emitObjectLiteralExpression(node); - case 202 /* PropertyAccessExpression */: - return emitPropertyAccessExpression(node); - case 203 /* ElementAccessExpression */: - return emitElementAccessExpression(node); - case 204 /* CallExpression */: - return emitCallExpression(node); - case 205 /* NewExpression */: - return emitNewExpression(node); - case 206 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 207 /* TypeAssertionExpression */: - return emitTypeAssertionExpression(node); - case 208 /* ParenthesizedExpression */: - return emitParenthesizedExpression(node); - case 209 /* FunctionExpression */: - return emitFunctionExpression(node); - case 210 /* ArrowFunction */: - return emitArrowFunction(node); - case 211 /* DeleteExpression */: - return emitDeleteExpression(node); - case 212 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 213 /* VoidExpression */: - return emitVoidExpression(node); - case 214 /* AwaitExpression */: - return emitAwaitExpression(node); - case 215 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 216 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 217 /* BinaryExpression */: - return emitBinaryExpression(node); - case 218 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 219 /* TemplateExpression */: - return emitTemplateExpression(node); - case 220 /* YieldExpression */: - return emitYieldExpression(node); - case 221 /* SpreadElement */: - return emitSpreadExpression(node); - case 222 /* ClassExpression */: - return emitClassExpression(node); - case 223 /* OmittedExpression */: - return; - case 224 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(node); - case 225 /* AsExpression */: - return emitAsExpression(node); - case 226 /* NonNullExpression */: - return emitNonNullExpression(node); - case 227 /* MetaProperty */: - return emitMetaProperty(node); - case 228 /* SyntheticExpression */: - ts.Debug.fail("SyntheticExpression should never be printed."); - break; - // Misc - case 229 /* TemplateSpan */: - return emitTemplateSpan(node); - case 230 /* SemicolonClassElement */: - return emitSemicolonClassElement(); - // Element - case 231 /* Block */: - return emitBlock(node); - case 232 /* EmptyStatement */: - return emitEmptyStatement(/*isEmbeddedStatement*/ false); - case 233 /* VariableStatement */: - return emitVariableStatement(node); - case 234 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 235 /* IfStatement */: - return emitIfStatement(node); - case 236 /* DoStatement */: - return emitDoStatement(node); - case 237 /* WhileStatement */: - return emitWhileStatement(node); - case 238 /* ForStatement */: - return emitForStatement(node); - case 239 /* ForInStatement */: - return emitForInStatement(node); - case 240 /* ForOfStatement */: - return emitForOfStatement(node); - case 241 /* ContinueStatement */: - return emitContinueStatement(node); - case 242 /* BreakStatement */: - return emitBreakStatement(node); - case 243 /* ReturnStatement */: - return emitReturnStatement(node); - case 244 /* WithStatement */: - return emitWithStatement(node); - case 245 /* SwitchStatement */: - return emitSwitchStatement(node); - case 246 /* LabeledStatement */: - return emitLabeledStatement(node); - case 247 /* ThrowStatement */: - return emitThrowStatement(node); - case 248 /* TryStatement */: - return emitTryStatement(node); - case 249 /* DebuggerStatement */: - return emitDebuggerStatement(node); - // Declarations - case 250 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 251 /* VariableDeclarationList */: - return emitVariableDeclarationList(node); - case 252 /* FunctionDeclaration */: - return emitFunctionDeclaration(node); - case 253 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 254 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 255 /* TypeAliasDeclaration */: - return emitTypeAliasDeclaration(node); - case 256 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 257 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 258 /* ModuleBlock */: - return emitModuleBlock(node); - case 259 /* CaseBlock */: - return emitCaseBlock(node); - case 260 /* NamespaceExportDeclaration */: - return emitNamespaceExportDeclaration(node); - case 261 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 262 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 263 /* ImportClause */: - return emitImportClause(node); - case 264 /* NamespaceImport */: - return emitNamespaceImport(node); - case 265 /* NamedImports */: - return emitNamedImports(node); - case 266 /* ImportSpecifier */: - return emitImportSpecifier(node); - case 267 /* ExportAssignment */: - return emitExportAssignment(node); - case 268 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 269 /* NamedExports */: - return emitNamedExports(node); - case 270 /* NamespaceExport */: - return emitNamespaceExport(node); - case 271 /* ExportSpecifier */: - return emitExportSpecifier(node); - case 272 /* MissingDeclaration */: - return; - // Module references - case 273 /* ExternalModuleReference */: - return emitExternalModuleReference(node); - // JSX - case 274 /* JsxElement */: - return emitJsxElement(node); - case 275 /* JsxSelfClosingElement */: - return emitJsxSelfClosingElement(node); - case 278 /* JsxFragment */: - return emitJsxFragment(node); - case 276 /* JsxOpeningElement */: - case 279 /* JsxOpeningFragment */: - return emitJsxOpeningElementOrFragment(node); - case 277 /* JsxClosingElement */: - case 280 /* JsxClosingFragment */: - return emitJsxClosingElementOrFragment(node); - case 281 /* JsxAttribute */: - return emitJsxAttribute(node); - case 282 /* JsxAttributes */: - return emitJsxAttributes(node); - case 283 /* JsxSpreadAttribute */: - return emitJsxSpreadAttribute(node); - case 284 /* JsxExpression */: - return emitJsxExpression(node); - // Clauses - case 285 /* CaseClause */: - return emitCaseClause(node); - case 286 /* DefaultClause */: - return emitDefaultClause(node); - case 287 /* HeritageClause */: - return emitHeritageClause(node); - case 288 /* CatchClause */: - return emitCatchClause(node); - // Property assignments - case 289 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 290 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 291 /* SpreadAssignment */: - return emitSpreadAssignment(node); - // Enum - case 292 /* EnumMember */: - return emitEnumMember(node); - // Unparsed - case 293 /* UnparsedPrologue */: - return writeUnparsedNode(node); - case 300 /* UnparsedSource */: - case 294 /* UnparsedPrepend */: - return emitUnparsedSourceOrPrepend(node); - case 295 /* UnparsedText */: - case 296 /* UnparsedInternalText */: - return emitUnparsedTextLike(node); - case 297 /* UnparsedSyntheticReference */: - return emitUnparsedSyntheticReference(node); - // Top-level nodes - case 298 /* SourceFile */: - return emitSourceFile(node); - case 299 /* Bundle */: - ts.Debug.fail("Bundles should be printed using printBundle"); - break; - // SyntaxKind.UnparsedSource (handled above) - case 301 /* InputFiles */: - ts.Debug.fail("InputFiles should not be printed"); - break; - // JSDoc nodes (only used in codefixes currently) - case 302 /* JSDocTypeExpression */: - return emitJSDocTypeExpression(node); - case 303 /* JSDocNameReference */: - return emitJSDocNameReference(node); - case 304 /* JSDocAllType */: - return writePunctuation("*"); - case 305 /* JSDocUnknownType */: - return writePunctuation("?"); - case 306 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 307 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 308 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 309 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 182 /* RestType */: - case 310 /* JSDocVariadicType */: - return emitRestOrJSDocVariadicType(node); - // SyntaxKind.JSDocNamepathType (missing) - case 312 /* JSDocComment */: - return emitJSDoc(node); - case 314 /* JSDocTypeLiteral */: - return emitJSDocTypeLiteral(node); - case 315 /* JSDocSignature */: - return emitJSDocSignature(node); - case 317 /* JSDocTag */: - case 322 /* JSDocClassTag */: - return emitJSDocSimpleTag(node); - case 318 /* JSDocAugmentsTag */: - case 319 /* JSDocImplementsTag */: - return emitJSDocHeritageTag(node); - // SyntaxKind.JSDocAuthorTag (missing) - // SyntaxKind.JSDocDeprecatedTag (missing) - // SyntaxKind.JSDocClassTag (see JSDocTag, above) - // SyntaxKind.JSDocPublicTag (missing) - // SyntaxKind.JSDocPrivateTag (missing) - // SyntaxKind.JSDocProtectedTag (missing) - // SyntaxKind.JSDocReadonlyTag (missing) - case 328 /* JSDocCallbackTag */: - return emitJSDocCallbackTag(node); - // SyntaxKind.JSDocEnumTag (see below) - case 330 /* JSDocParameterTag */: - case 337 /* JSDocPropertyTag */: - return emitJSDocPropertyLikeTag(node); - case 329 /* JSDocEnumTag */: - case 331 /* JSDocReturnTag */: - case 332 /* JSDocThisTag */: - case 333 /* JSDocTypeTag */: - return emitJSDocSimpleTypedTag(node); - case 334 /* JSDocTemplateTag */: - return emitJSDocTemplateTag(node); - case 335 /* JSDocTypedefTag */: - return emitJSDocTypedefTag(node); - case 336 /* JSDocSeeTag */: - return emitJSDocSeeTag(node); - // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) - // Synthesized list - case 338 /* SyntaxList */: - ts.Debug.fail("SyntaxList should not be printed"); - break; - // Transformation nodes - case 339 /* NotEmittedStatement */: - break; - case 340 /* PartiallyEmittedExpression */: - return emitPartiallyEmittedExpression(node); - case 341 /* CommaListExpression */: - return emitCommaList(node); - case 342 /* MergeDeclarationMarker */: - case 343 /* EndOfDeclarationMarker */: - break; - case 344 /* SyntheticReferenceExpression */: - ts.Debug.fail("SyntheticReferenceExpression should not be printed"); + function pipelineEmitWithHintWorker(hint, node) { + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 6 /* JsxAttributeValue */) + return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } + if (hint === 4 /* Unspecified */) { + switch (node.kind) { + // Pseudo-literals + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return emitLiteral(node, /*jsxAttributeEscape*/ false); + // Identifiers + case 78 /* Identifier */: + return emitIdentifier(node); + // PrivateIdentifiers + case 79 /* PrivateIdentifier */: + return emitPrivateIdentifier(node); + // Parse tree nodes + // Names + case 158 /* QualifiedName */: + return emitQualifiedName(node); + case 159 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 160 /* TypeParameter */: + return emitTypeParameter(node); + case 161 /* Parameter */: + return emitParameter(node); + case 162 /* Decorator */: + return emitDecorator(node); + // Type members + case 163 /* PropertySignature */: + return emitPropertySignature(node); + case 164 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 165 /* MethodSignature */: + return emitMethodSignature(node); + case 166 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 167 /* Constructor */: + return emitConstructor(node); + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 170 /* CallSignature */: + return emitCallSignature(node); + case 171 /* ConstructSignature */: + return emitConstructSignature(node); + case 172 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 173 /* TypePredicate */: + return emitTypePredicate(node); + case 174 /* TypeReference */: + return emitTypeReference(node); + case 175 /* FunctionType */: + return emitFunctionType(node); + case 176 /* ConstructorType */: + return emitConstructorType(node); + case 177 /* TypeQuery */: + return emitTypeQuery(node); + case 178 /* TypeLiteral */: + return emitTypeLiteral(node); + case 179 /* ArrayType */: + return emitArrayType(node); + case 180 /* TupleType */: + return emitTupleType(node); + case 181 /* OptionalType */: + return emitOptionalType(node); + // SyntaxKind.RestType is handled below + case 183 /* UnionType */: + return emitUnionType(node); + case 184 /* IntersectionType */: + return emitIntersectionType(node); + case 185 /* ConditionalType */: + return emitConditionalType(node); + case 186 /* InferType */: + return emitInferType(node); + case 187 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 224 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 188 /* ThisType */: + return emitThisType(); + case 189 /* TypeOperator */: + return emitTypeOperator(node); + case 190 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 191 /* MappedType */: + return emitMappedType(node); + case 192 /* LiteralType */: + return emitLiteralType(node); + case 193 /* NamedTupleMember */: + return emitNamedTupleMember(node); + case 194 /* TemplateLiteralType */: + return emitTemplateType(node); + case 195 /* TemplateLiteralTypeSpan */: + return emitTemplateTypeSpan(node); + case 196 /* ImportType */: + return emitImportTypeNode(node); + // Binding patterns + case 197 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 198 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 199 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 229 /* TemplateSpan */: + return emitTemplateSpan(node); + case 230 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 231 /* Block */: + return emitBlock(node); + case 233 /* VariableStatement */: + return emitVariableStatement(node); + case 232 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 234 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 235 /* IfStatement */: + return emitIfStatement(node); + case 236 /* DoStatement */: + return emitDoStatement(node); + case 237 /* WhileStatement */: + return emitWhileStatement(node); + case 238 /* ForStatement */: + return emitForStatement(node); + case 239 /* ForInStatement */: + return emitForInStatement(node); + case 240 /* ForOfStatement */: + return emitForOfStatement(node); + case 241 /* ContinueStatement */: + return emitContinueStatement(node); + case 242 /* BreakStatement */: + return emitBreakStatement(node); + case 243 /* ReturnStatement */: + return emitReturnStatement(node); + case 244 /* WithStatement */: + return emitWithStatement(node); + case 245 /* SwitchStatement */: + return emitSwitchStatement(node); + case 246 /* LabeledStatement */: + return emitLabeledStatement(node); + case 247 /* ThrowStatement */: + return emitThrowStatement(node); + case 248 /* TryStatement */: + return emitTryStatement(node); + case 249 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 250 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 251 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 252 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 253 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 254 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 255 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 256 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 257 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 258 /* ModuleBlock */: + return emitModuleBlock(node); + case 259 /* CaseBlock */: + return emitCaseBlock(node); + case 260 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 261 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 262 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 263 /* ImportClause */: + return emitImportClause(node); + case 264 /* NamespaceImport */: + return emitNamespaceImport(node); + case 270 /* NamespaceExport */: + return emitNamespaceExport(node); + case 265 /* NamedImports */: + return emitNamedImports(node); + case 266 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 267 /* ExportAssignment */: + return emitExportAssignment(node); + case 268 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 269 /* NamedExports */: + return emitNamedExports(node); + case 271 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 272 /* MissingDeclaration */: + return; + // Module references + case 273 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 11 /* JsxText */: + return emitJsxText(node); + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 277 /* JsxClosingElement */: + case 280 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 281 /* JsxAttribute */: + return emitJsxAttribute(node); + case 282 /* JsxAttributes */: + return emitJsxAttributes(node); + case 283 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 284 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 285 /* CaseClause */: + return emitCaseClause(node); + case 286 /* DefaultClause */: + return emitDefaultClause(node); + case 287 /* HeritageClause */: + return emitHeritageClause(node); + case 288 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 289 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 290 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 291 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 292 /* EnumMember */: + return emitEnumMember(node); + // Unparsed + case 293 /* UnparsedPrologue */: + return writeUnparsedNode(node); + case 300 /* UnparsedSource */: + case 294 /* UnparsedPrepend */: + return emitUnparsedSourceOrPrepend(node); + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: + return emitUnparsedTextLike(node); + case 297 /* UnparsedSyntheticReference */: + return emitUnparsedSyntheticReference(node); + // Top-level nodes + case 298 /* SourceFile */: + return emitSourceFile(node); + case 299 /* Bundle */: + return ts.Debug.fail("Bundles should be printed using printBundle"); + // SyntaxKind.UnparsedSource (handled above) + case 301 /* InputFiles */: + return ts.Debug.fail("InputFiles should not be printed"); + // JSDoc nodes (only used in codefixes currently) + case 302 /* JSDocTypeExpression */: + return emitJSDocTypeExpression(node); + case 303 /* JSDocNameReference */: + return emitJSDocNameReference(node); + case 304 /* JSDocAllType */: + return writePunctuation("*"); + case 305 /* JSDocUnknownType */: + return writePunctuation("?"); + case 306 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 307 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 308 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 309 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 182 /* RestType */: + case 310 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + case 311 /* JSDocNamepathType */: + return; + case 312 /* JSDocComment */: + return emitJSDoc(node); + case 314 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 315 /* JSDocSignature */: + return emitJSDocSignature(node); + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + return emitJSDocSimpleTag(node); + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + return emitJSDocHeritageTag(node); + case 320 /* JSDocAuthorTag */: + case 321 /* JSDocDeprecatedTag */: + return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 327 /* JSDocOverrideTag */: + return; + case 328 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + // SyntaxKind.JSDocEnumTag (see below) + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 329 /* JSDocEnumTag */: + case 331 /* JSDocReturnTag */: + case 332 /* JSDocThisTag */: + case 333 /* JSDocTypeTag */: + return emitJSDocSimpleTypedTag(node); + case 334 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 335 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 336 /* JSDocSeeTag */: + return emitJSDocSeeTag(node); + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) + // Transformation nodes + case 339 /* NotEmittedStatement */: + case 343 /* EndOfDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: + return; + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + if (substituteNode !== ts.noEmitSubstitution) { + var substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } + } + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node, /*jsxAttributeEscape*/ false); + // Identifiers + case 78 /* Identifier */: + return emitIdentifier(node); + // Expressions + case 200 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 201 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 202 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 203 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 204 /* CallExpression */: + return emitCallExpression(node); + case 205 /* NewExpression */: + return emitNewExpression(node); + case 206 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 207 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 208 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 209 /* FunctionExpression */: + return emitFunctionExpression(node); + case 210 /* ArrowFunction */: + return emitArrowFunction(node); + case 211 /* DeleteExpression */: + return emitDeleteExpression(node); + case 212 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 213 /* VoidExpression */: + return emitVoidExpression(node); + case 214 /* AwaitExpression */: + return emitAwaitExpression(node); + case 215 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 216 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 217 /* BinaryExpression */: + return emitBinaryExpression(node); + case 218 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 219 /* TemplateExpression */: + return emitTemplateExpression(node); + case 220 /* YieldExpression */: + return emitYieldExpression(node); + case 221 /* SpreadElement */: + return emitSpreadElement(node); + case 222 /* ClassExpression */: + return emitClassExpression(node); + case 223 /* OmittedExpression */: + return; + case 225 /* AsExpression */: + return emitAsExpression(node); + case 226 /* NonNullExpression */: + return emitNonNullExpression(node); + case 227 /* MetaProperty */: + return emitMetaProperty(node); + case 228 /* SyntheticExpression */: + return ts.Debug.fail("SyntheticExpression should never be printed."); + // JSX + case 274 /* JsxElement */: + return emitJsxElement(node); + case 275 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 278 /* JsxFragment */: + return emitJsxFragment(node); + // Synthesized list + case 338 /* SyntaxList */: + return ts.Debug.fail("SyntaxList should not be printed"); + // Transformation nodes + case 339 /* NotEmittedStatement */: + return; + case 340 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 341 /* CommaListExpression */: + return emitCommaList(node); + case 342 /* MergeDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: + return; + case 344 /* SyntheticReferenceExpression */: + return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); + } } if (ts.isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); if (ts.isTokenKind(node.kind)) return writeTokenNode(node, writePunctuation); + ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); } function emitMappedTypeParameter(node) { emit(node.name); @@ -104160,6 +104715,13 @@ var ts; writeSpace(); emit(node.constraint); } + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node); + ts.Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); + } function getHelpersFromBundledSourceFiles(bundle) { var result; if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) { @@ -104262,9 +104824,6 @@ var ts; writeStringLiteral(text); } } - function emitStringLiteralWithJsxAttributeEscape(node) { - emitLiteral(node, /*jsxAttributeEscape*/ true); - } // SyntaxKind.UnparsedSource // SyntaxKind.UnparsedPrepend function emitUnparsedSourceOrPrepend(unparsed) { @@ -104323,7 +104882,7 @@ var ts; } function emitEntityName(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -104331,7 +104890,7 @@ var ts; } function emitComputedPropertyName(node) { writePunctuation("["); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } // @@ -104365,11 +104924,11 @@ 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); + 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); } function emitDecorator(decorator) { writePunctuation("@"); - emit(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } // // Type members @@ -104534,7 +105093,7 @@ var ts; writePunctuation("}"); } function emitArrayType(node) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -104557,21 +105116,21 @@ var ts; emit(node.type); } function emitOptionalType(node) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 516 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node) { - emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -104597,10 +105156,10 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -104623,7 +105182,7 @@ var ts; writeSpace(); } writePunctuation("["); - emitWithContext(node.typeParameter, emitMappedTypeParameter); + pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter); if (node.nameType) { writeSpace(); writeKeyword("as"); @@ -104651,7 +105210,7 @@ var ts; writePunctuation("}"); } function emitLiteralType(node) { - emit(node.literal); + emitExpression(node.literal); } function emitTemplateType(node) { emit(node.head); @@ -104693,7 +105252,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // Expressions @@ -104701,7 +105260,7 @@ var ts; function emitArrayLiteralExpression(node) { var elements = node.elements; var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; - emitList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -104717,7 +105276,7 @@ var ts; } } function emitPropertyAccessExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos); var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); var linesAfterDot = getLinesBetweenNodes(node, token, node.name); @@ -104759,41 +105318,41 @@ var ts; } } function emitElementAccessExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); - emit(node.argumentExpression); + emitExpression(node.argumentExpression); emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitList(node, node.arguments, 2576 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitList(node, node.arguments, 18960 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node) { - emit(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); - emit(node.template); + emitExpression(node.template); } function emitTypeAssertionExpression(node) { writePunctuation("<"); emit(node.type); writePunctuation(">"); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emit(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -104817,29 +105376,29 @@ var ts; function emitDeleteExpression(node) { emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node) { writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emit(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node) { // In some cases, we need to emit a space between the operator and the operand. One obvious case @@ -104860,11 +105419,11 @@ var ts; || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { - emit(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } function createEmitBinaryExpression() { - return ts.createBinaryExpressionTrampoline(onEnter, maybeEmitExpression, onOperator, maybeEmitExpression, onExit, /*foldState*/ undefined); + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); function onEnter(node, state) { if (state) { state.stackIndex++; @@ -104874,7 +105433,12 @@ var ts; state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); - beforeEmitWithContext(node, emitComments_1, emitSourceMaps); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (emitComments_1) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); } else { state = { @@ -104889,6 +105453,9 @@ var ts; } return state; } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } function onOperator(operatorToken, _state, node) { var isCommaOperator = operatorToken.kind !== 27 /* CommaToken */; var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); @@ -104899,6 +105466,9 @@ var ts; emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } function onExit(node, state) { var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); @@ -104910,16 +105480,35 @@ var ts; var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex]; var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex]; - afterEmitWithContext(node, shouldEmitComments_1, shouldEmitSourceMaps_1, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines); + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps_1) + emitSourceMapsAfterNode(node); + if (shouldEmitComments_1) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); state.stackIndex--; } } - function maybeEmitExpression(next) { - // Push a new frame for binary expressions, otherwise emit all other expressions. - if (ts.isBinaryExpression(next)) { - return next; + function maybeEmitExpression(next, parent, side) { + var parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); + var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next); + if (pipelinePhase === pipelineEmitWithSubstitution) { + ts.Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression)); + pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next); + lastSubstitution = undefined; } - emit(next); + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (ts.isBinaryExpression(next)) { + return next; + } + } + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1 /* Expression */, next); } } function emitConditionalExpression(node) { @@ -104927,16 +105516,16 @@ var ts; var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emit(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true); - emit(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true); - emit(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { @@ -104946,22 +105535,22 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node) { + function emitSpreadElement(node) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emit(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -104970,7 +105559,7 @@ var ts; } } function emitNonNullExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } function emitMetaProperty(node) { @@ -104982,7 +105571,7 @@ var ts; // Misc // function emitTemplateSpan(node) { - emit(node.expression); + emitExpression(node.expression); emit(node.literal); } // @@ -105012,11 +105601,8 @@ var ts; writeTrailingSemicolon(); } } - function emitEmbeddedEmptyStatement(_node) { - emitEmptyStatement(/*isEmbeddedStatement*/ true); - } function emitExpressionStatement(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); // Emit semicolon in non json files // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { @@ -105027,7 +105613,7 @@ var ts; var openParenPos = emitTokenWithComment(98 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { @@ -105046,7 +105632,7 @@ var ts; var openParenPos = emitTokenWithComment(114 /* WhileKeyword */, startPos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); } function emitDoStatement(node) { @@ -105085,7 +105671,7 @@ var ts; writeSpace(); emitTokenWithComment(100 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -105098,7 +105684,7 @@ var ts; writeSpace(); emitTokenWithComment(157 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -105108,7 +105694,7 @@ var ts; emit(node); } else { - emit(node); + emitExpression(node); } } } @@ -105155,7 +105741,7 @@ var ts; var openParenPos = emitTokenWithComment(115 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -105163,7 +105749,7 @@ var ts; var openParenPos = emitTokenWithComment(106 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); @@ -105205,7 +105791,7 @@ var ts; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); @@ -105221,7 +105807,7 @@ var ts; writeKeyword("function"); emit(node.asteriskToken); writeSpace(); - emit(node.name); + emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } function emitSignatureAndBody(node, emitSignatureHead) { @@ -105245,7 +105831,7 @@ var ts; else { emitSignatureHead(node); writeSpace(); - emit(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -105320,7 +105906,7 @@ var ts; increaseIndent(); } else { - emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, /*parenthesizerRule*/ undefined, statementOffset); } } function emitClassDeclaration(node) { @@ -105333,7 +105919,7 @@ var ts; writeKeyword("class"); if (node.name) { writeSpace(); - emit(node.name); + emitIdentifierName(node.name); } var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { @@ -105431,7 +106017,7 @@ var ts; } function emitModuleReference(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -105447,7 +106033,7 @@ var ts; emitTokenWithComment(153 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } - emit(node.moduleSpecifier); + emitExpression(node.moduleSpecifier); writeTrailingSemicolon(); } function emitImportClause(node) { @@ -105485,7 +106071,9 @@ var ts; emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); - emit(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(62 /* EqualsToken */) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -105506,7 +106094,7 @@ var ts; var fromPos = node.exportClause ? node.exportClause.end : nextPos; emitTokenWithComment(153 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); - emit(node.moduleSpecifier); + emitExpression(node.moduleSpecifier); } writeTrailingSemicolon(); } @@ -105553,7 +106141,7 @@ var ts; function emitExternalModuleReference(node) { writeKeyword("require"); writePunctuation("("); - emit(node.expression); + emitExpression(node.expression); writePunctuation(")"); } // @@ -105605,17 +106193,13 @@ var ts; function emitJsxAttributes(node) { emitList(node, node.properties, 262656 /* JsxElementAttributes */); } - function emitJsxAttributeValue(node) { - var emitCallback = ts.isStringLiteral(node) ? emitStringLiteralWithJsxAttributeEscape : emitWorker; - emitWithContext(node, emitCallback); - } function emitJsxAttribute(node) { emit(node.name); emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue); } function emitJsxSpreadAttribute(node) { writePunctuation("{..."); - emit(node.expression); + emitExpression(node.expression); writePunctuation("}"); } function hasTrailingCommentsAtPosition(pos) { @@ -105640,7 +106224,7 @@ var ts; } var end = emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); emit(node.dotDotDotToken); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(19 /* CloseBraceToken */, ((_a = node.expression) === null || _a === void 0 ? void 0 : _a.end) || end, writePunctuation, node); if (isMultiline) { writer.decreaseIndent(); @@ -105649,7 +106233,7 @@ var ts; } function emitJsxTagName(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -105661,7 +106245,7 @@ var ts; function emitCaseClause(node) { emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { @@ -105722,7 +106306,7 @@ var ts; var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emit(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node) { emit(node.name); @@ -105730,13 +106314,13 @@ var ts; writeSpace(); writePunctuation("="); writeSpace(); - emit(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node) { if (node.expression) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } // @@ -105744,7 +106328,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // JSDoc @@ -105989,15 +106573,15 @@ var ts; emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + emitList(node, statements, 1 /* MultiLine */, /*parenthesizerRule*/ undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } // Transformation nodes function emitPartiallyEmittedExpression(node) { - emit(node.expression); + emitExpression(node.expression); } function emitCommaList(node) { - emitList(node, node.elements, 528 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -106143,12 +106727,12 @@ var ts; emit(node); } } - function emitInitializer(node, equalCommentStartPos, container) { + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); - emit(node); + emitExpression(node, parenthesizerRule); } } function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { @@ -106163,10 +106747,10 @@ var ts; emit(node); } } - function emitExpressionWithLeadingSpace(node) { + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { if (node) { writeSpace(); - emit(node); + emitExpression(node, parenthesizerRule); } } function emitWithTrailingSpace(node) { @@ -106184,7 +106768,7 @@ var ts; writeLine(); increaseIndent(); if (ts.isEmptyStatement(node)) { - emitWithContext(node, emitEmbeddedEmptyStatement); + pipelineEmit(5 /* EmbeddedStatement */, node); } else { emit(node); @@ -106196,7 +106780,7 @@ var ts; emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures @@ -106257,7 +106841,13 @@ var ts; break; } } - function emitList(parentNode, children, format, start, count) { + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; @@ -106361,7 +106951,12 @@ var ts; shouldEmitInterveningComments = mayEmitInterveningComments; } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); shouldDecreaseIndentAfterEmit = false; @@ -107097,6 +107692,33 @@ var ts; return node; } // Comments + function pipelineEmitWithComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit leading comments + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit trailing comments + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; @@ -107392,6 +108014,50 @@ var ts; } return node.parsedSourceMap || undefined; } + function pipelineEmitWithSourceMaps(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node); + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit leading sourcemap + if (ts.isUnparsedNode(node)) { + ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); + var parsed = getParsedSourceMap(node.parent); + if (parsed && sourceMapGenerator) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); + } + } + else { + var source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 339 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + } + } + } + function emitSourceMapsAfterNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit trailing sourcemap + if (!ts.isUnparsedNode(node)) { + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = false; + } + if (node.kind !== 339 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); + } + } + } /** * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source */ @@ -107484,736 +108150,6 @@ var ts; } } ts.createPrinter = createPrinter; - var PreprintPipelinePhase; - (function (PreprintPipelinePhase) { - PreprintPipelinePhase[PreprintPipelinePhase["Notification"] = 0] = "Notification"; - PreprintPipelinePhase[PreprintPipelinePhase["Substitution"] = 1] = "Substitution"; - PreprintPipelinePhase[PreprintPipelinePhase["Visit"] = 2] = "Visit"; - })(PreprintPipelinePhase || (PreprintPipelinePhase = {})); - function createPreprinter(handlers) { - var _a = handlers.substituteNode, substituteNode = _a === void 0 ? ts.noEmitSubstitution : _a, _b = handlers.onEmitNode, onEmitNode = _b === void 0 ? ts.noEmitNotification : _b, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled; - var pipelineResult; - // Outer visitors - // - // These visitors are invoked by inner visitors to re-enter the pipeline - // for notification and substitution. - var visit = makeVisitor(pipelineVisitorForUnspecified); - var visitSourceFile = makeVisitor(pipelineVisitorForSourceFile, ts.isSourceFile); - var visitIdentifierName = makeVisitor(pipelineVisitorForIdentifierName, ts.isIdentifier); - var visitModuleName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isModuleName); - var visitPropertyName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isPropertyName); - var visitMemberName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isMemberName); - var visitBindingName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isBindingName); - var visitEntityName = makeVisitor(pipelineVisitorForIdentifierReferenceOrUnspecified, ts.isEntityName); - var visitExpression = makeVisitor(pipelineVisitorForExpression, ts.isExpression); - var visitForInitializer = makeVisitor(pipelineVisitorForForInitializer, ts.isForInitializer); - var visitTypeNode = makeVisitor(pipelineVisitorForUnspecified, ts.isTypeNode); - var visitEmbeddedStatement = makeVisitor(pipelineVisitorForEmbeddedStatement, ts.isStatement, ts.factory.liftToBlock); - var visitJsxAttributeValue = makeVisitor(pipelineVisitorForJsxAttributeValue, ts.isStringLiteralOrJsxExpression); - var visitMappedTypeParameter = makeVisitor(pipelineVisitorForMappedTypeParameter, ts.isTypeParameterDeclaration); - var visitConciseBody = makeVisitor(pipelineVisitorForConciseBody, ts.isConciseBody); - var visitFunctionBody = makeVisitor(pipelineVisitorForUnspecified, ts.isFunctionBody); - var visitList = makeListVisitor(pipelineVisitorForUnspecified); - var visitTypeNodeList = makeListVisitor(pipelineVisitorForUnspecified, ts.isTypeNode); - var visitExpressionList = makeListVisitor(pipelineVisitorForExpression, ts.isExpression); - var visitParameterList = makeListVisitor(pipelineVisitorForUnspecified, ts.isParameter); - function makeVisitor(outerVisitor, defaultTest, lift) { - function visit(node, test) { - return ts.visitNode(node, outerVisitor, test || defaultTest, lift); - } - return visit; - } - function makeListVisitor(outerVisitor, defaultTest) { - function visitList(nodes, test) { - if (test === void 0) { test = defaultTest || ts.returnTrue; } - return ts.visitNodes(nodes, outerVisitor, test); - } - return visitList; - } - // Pipeline Visitors - // - // These visitors execute our existing pipeline logic for notification and substitution, - // but adapted to our visitor pattern. In some cases, we refine the `EmitHint` we pass - // to the `onEmitNode` and `substituteNode` APIs to ensure they receive the appropriate - // context. - // - // For example, the ConciseBody of an arrow function could be an Identifier, in which - // case we would want to use `EmitHint.Expression` to ensure we treat the identifier - // as an expression during substitution. - function pipelineVisitorForSourceFile(node) { return pipelineVisitorWorker(0 /* SourceFile */, node); } - function pipelineVisitorForExpression(node) { return pipelineVisitorWorker(1 /* Expression */, node); } - function pipelineVisitorForIdentifierName(node) { return pipelineVisitorWorker(2 /* IdentifierName */, node); } - function pipelineVisitorForIdentifierNameOrUnspecified(node) { return pipelineVisitorWorker(ts.isIdentifier(node) ? 2 /* IdentifierName */ : 4 /* Unspecified */, node); } - function pipelineVisitorForIdentifierReferenceOrUnspecified(node) { return pipelineVisitorWorker(ts.isIdentifier(node) ? 1 /* Expression */ : 4 /* Unspecified */, node); } - function pipelineVisitorForForInitializer(node) { return pipelineVisitorWorker(ts.isVariableDeclarationList(node) ? 4 /* Unspecified */ : 1 /* Expression */, node); } - function pipelineVisitorForMappedTypeParameter(node) { return pipelineVisitorWorker(3 /* MappedTypeParameter */, node); } - function pipelineVisitorForEmbeddedStatement(node) { return pipelineVisitorWorker(ts.isEmptyStatement(node) ? 5 /* EmbeddedStatement */ : 4 /* Unspecified */, node); } - function pipelineVisitorForJsxAttributeValue(node) { return pipelineVisitorWorker(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); } - function pipelineVisitorForConciseBody(node) { return pipelineVisitorWorker(ts.isBlock(node) ? 4 /* Unspecified */ : 1 /* Expression */, node); } - function pipelineVisitorForUnspecified(node) { return pipelineVisitorWorker(4 /* Unspecified */, node); } - /** - * Adapts the emit pipeline API to work with the visitor API - */ - function pipelineVisitorWorker(hint, node) { - resetPipelineResult(); - // Get the first supported pipeline phase for this node and evaluate it. We can skip several stack - // frames if we aren't doing emit notification, so we check for substitution and direct callbacks - // and execute those immediately. - var pipelinePhase = getPipelinePhase(0 /* Notification */, node); - if (pipelinePhase === pipelineVisitDirect) { - return visitor(hint, node); - } - if (pipelinePhase === pipelineVisitWithSubstitution) { - // The next phase after substitution is always direct visitation, so we can reduce the call stack - // depth by calling the visitor directly. - return visitor(hint, substituteNode(hint, node)); - } - pipelinePhase(hint, node); - ts.Debug.assertIsDefined(pipelineResult); - var result = pipelineResult; - resetPipelineResult(); - return result; - } - function resetPipelineResult() { - pipelineResult = undefined; - } - /** - * Gets the pipeline callback to pass to the relevant API (i.e., `substituteNode` or `onEmitNode`) - */ - function getPipelinePhase(phase, node) { - switch (phase) { - case 0 /* Notification */: - if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { - return pipelineVisitWithNotification; - } - // falls through - case 1 /* Substitution */: - if (substituteNode !== ts.noEmitSubstitution) { - return pipelineVisitWithSubstitution; - } - // falls through - default: - return pipelineVisitDirect; - } - } - /** - * A callback that can be evaluated to trigger emit notification as part of the emit pipeline. - */ - function pipelineVisitWithNotification(hint, node) { - onEmitNode(hint, node, getPipelinePhase(1 /* Substitution */, node)); - } - /** - * A callback that can be evaluated to trigger JIT substitution as part of the emit pipeline. - */ - function pipelineVisitWithSubstitution(hint, node) { - // Next phase is always direct visitation, so we can reduce the call stack - // depth by calling the visitor directly. - pipelineResult = visitor(hint, substituteNode(hint, node)); - } - /** - * A callback that can be evaluated to visit the subtree of a node. - */ - function pipelineVisitDirect(hint, node) { - pipelineResult = visitor(hint, node); - } - /** - * Re-enters the visitor pattern from the pipeline pattern to perform - * tree updates and trigger parenthesization rules. - */ - function visitor(hint, node) { - // This should align with the assertions in `pipelineEmitWithHint`. - if (hint === 0 /* SourceFile */) - return preprintSourceFile(ts.cast(node, ts.isSourceFile)); - if (hint === 2 /* IdentifierName */) - return preprintIdentifier(ts.cast(node, ts.isIdentifier)); - if (hint === 6 /* JsxAttributeValue */) - return ts.cast(node, ts.isStringLiteral); - if (hint === 3 /* MappedTypeParameter */) - return preprintTypeParameterDeclaration(ts.cast(node, ts.isTypeParameterDeclaration)); - if (hint === 5 /* EmbeddedStatement */) - return ts.cast(node, ts.isEmptyStatement); - var kind = node.kind; - // No need to visit nodes without children. - if ((kind > 0 /* FirstToken */ && kind <= 157 /* LastToken */) || kind === 188 /* ThisType */) { - return node; - } - if (hint === 4 /* Unspecified */) { - if (ts.isKeyword(node.kind)) - return node; - switch (node.kind) { - // Identifiers - case 78 /* Identifier */: - return preprintIdentifier(node); - // Names - case 158 /* QualifiedName */: - ts.Debug.type(node); - return ts.factory.updateQualifiedName(node, visitEntityName(node.left), visitIdentifierName(node.right)); - case 159 /* ComputedPropertyName */: - ts.Debug.type(node); - return ts.factory.updateComputedPropertyName(node, visitExpression(node.expression)); - // Signature elements - case 160 /* TypeParameter */: - return preprintTypeParameterDeclaration(node); - case 161 /* Parameter */: - ts.Debug.type(node); - return ts.factory.updateParameterDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.dotDotDotToken, ts.isDotDotDotToken), visitBindingName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 162 /* Decorator */: - ts.Debug.type(node); - return ts.factory.updateDecorator(node, visitExpression(node.expression)); - // Type members - case 163 /* PropertySignature */: - ts.Debug.type(node); - return ts.factory.updatePropertySignature(node, visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type)); - case 164 /* PropertyDeclaration */: - ts.Debug.type(node); - return ts.factory.updatePropertyDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken || node.exclamationToken, ts.isQuestionOrExclamationToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 165 /* MethodSignature */: - ts.Debug.type(node); - return ts.factory.updateMethodSignature(node, visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 166 /* MethodDeclaration */: - ts.Debug.type(node); - return ts.factory.updateMethodDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 167 /* Constructor */: - ts.Debug.type(node); - return ts.factory.updateConstructorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitParameterList(node.parameters), visitFunctionBody(node.body)); - case 168 /* GetAccessor */: - ts.Debug.type(node); - return ts.factory.updateGetAccessorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 169 /* SetAccessor */: - ts.Debug.type(node); - return ts.factory.updateSetAccessorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visitParameterList(node.parameters), visitFunctionBody(node.body)); - case 170 /* CallSignature */: - ts.Debug.type(node); - return ts.factory.updateCallSignature(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 171 /* ConstructSignature */: - ts.Debug.type(node); - return ts.factory.updateConstructSignature(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 172 /* IndexSignature */: - ts.Debug.type(node); - return ts.factory.updateIndexSignature(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitParameterList(node.parameters), visitTypeNode(node.type)); - // Types - case 173 /* TypePredicate */: - ts.Debug.type(node); - return ts.factory.updateTypePredicateNode(node, visit(node.assertsModifier, ts.isAssertsKeyword), visit(node.parameterName, ts.isIdentifierOrThisTypeNode), visitTypeNode(node.type)); - case 174 /* TypeReference */: - ts.Debug.type(node); - return ts.factory.updateTypeReferenceNode(node, visitEntityName(node.typeName), visitTypeNodeList(node.typeArguments)); - case 175 /* FunctionType */: - ts.Debug.type(node); - return ts.factory.updateFunctionTypeNode(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), ts.visitNodes(node.parameters, pipelineVisitorForUnspecified, ts.isParameterDeclaration), visitTypeNode(node.type)); - case 176 /* ConstructorType */: - ts.Debug.type(node); - return ts.factory.updateConstructorTypeNode(node, ts.visitNodes(node.modifiers, pipelineVisitorForUnspecified, ts.isModifier), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 177 /* TypeQuery */: - ts.Debug.type(node); - return ts.factory.updateTypeQueryNode(node, visitEntityName(node.exprName)); - case 178 /* TypeLiteral */: - ts.Debug.type(node); - return ts.factory.updateTypeLiteralNode(node, visitList(node.members, ts.isTypeElement)); - case 179 /* ArrayType */: - ts.Debug.type(node); - return ts.factory.updateArrayTypeNode(node, visitTypeNode(node.elementType)); - case 180 /* TupleType */: - ts.Debug.type(node); - return ts.factory.updateTupleTypeNode(node, visitTypeNodeList(node.elements)); - case 181 /* OptionalType */: - ts.Debug.type(node); - return ts.factory.updateOptionalTypeNode(node, visitTypeNode(node.type)); - case 182 /* RestType */: - ts.Debug.type(node); - return ts.factory.updateRestTypeNode(node, visitTypeNode(node.type)); - case 183 /* UnionType */: - ts.Debug.type(node); - return ts.factory.updateUnionTypeNode(node, visitTypeNodeList(node.types)); - case 184 /* IntersectionType */: - ts.Debug.type(node); - return ts.factory.updateIntersectionTypeNode(node, visitTypeNodeList(node.types)); - case 185 /* ConditionalType */: - ts.Debug.type(node); - return ts.factory.updateConditionalTypeNode(node, visitTypeNode(node.checkType), visitTypeNode(node.extendsType), visitTypeNode(node.trueType), visitTypeNode(node.falseType)); - case 186 /* InferType */: - ts.Debug.type(node); - return ts.factory.updateInferTypeNode(node, visit(node.typeParameter, ts.isTypeParameterDeclaration)); - case 196 /* ImportType */: - ts.Debug.type(node); - return ts.factory.updateImportTypeNode(node, visitTypeNode(node.argument), visitEntityName(node.qualifier), visitTypeNodeList(node.typeArguments), node.isTypeOf); - case 193 /* NamedTupleMember */: - ts.Debug.type(node); - return ts.factory.updateNamedTupleMember(node, visit(node.dotDotDotToken, ts.isDotDotDotToken), visitIdentifierName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type)); - case 187 /* ParenthesizedType */: - ts.Debug.type(node); - return ts.factory.updateParenthesizedType(node, visitTypeNode(node.type)); - case 224 /* ExpressionWithTypeArguments */: - ts.Debug.type(node); - return ts.factory.updateExpressionWithTypeArguments(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments)); - case 189 /* TypeOperator */: - ts.Debug.type(node); - return ts.factory.updateTypeOperatorNode(node, visitTypeNode(node.type)); - case 190 /* IndexedAccessType */: - ts.Debug.type(node); - return ts.factory.updateIndexedAccessTypeNode(node, visitTypeNode(node.objectType), visitTypeNode(node.indexType)); - case 191 /* MappedType */: - ts.Debug.type(node); - return ts.factory.updateMappedTypeNode(node, visit(node.readonlyToken, ts.isReadonlyKeywordOrPlusOrMinusToken), visitMappedTypeParameter(node.typeParameter), visitTypeNode(node.nameType), visit(node.questionToken, ts.isQuestionOrPlusOrMinusToken), visitTypeNode(node.type)); - case 192 /* LiteralType */: - ts.Debug.type(node); - return ts.factory.updateLiteralTypeNode(node, visitExpression(node.literal, ts.isLiteralTypeLikeExpression)); - case 194 /* TemplateLiteralType */: - ts.Debug.type(node); - return ts.factory.updateTemplateLiteralType(node, visit(node.head, ts.isTemplateHead), visitList(node.templateSpans, ts.isTemplateLiteralTypeSpan)); - case 195 /* TemplateLiteralTypeSpan */: - ts.Debug.type(node); - return ts.factory.updateTemplateLiteralTypeSpan(node, visitTypeNode(node.type), visit(node.literal, ts.isTemplateMiddleOrTemplateTail)); - // Binding patterns - case 197 /* ObjectBindingPattern */: - ts.Debug.type(node); - return ts.factory.updateObjectBindingPattern(node, visitList(node.elements, ts.isBindingElement)); - case 198 /* ArrayBindingPattern */: - ts.Debug.type(node); - return ts.factory.updateArrayBindingPattern(node, visitList(node.elements, ts.isArrayBindingElement)); - case 199 /* BindingElement */: - ts.Debug.type(node); - return ts.factory.updateBindingElement(node, visit(node.dotDotDotToken, ts.isDotDotDotToken), visitPropertyName(node.propertyName), visitBindingName(node.name), visitExpression(node.initializer)); - // Misc - case 229 /* TemplateSpan */: - ts.Debug.type(node); - return ts.factory.updateTemplateSpan(node, visitExpression(node.expression), visit(node.literal, ts.isTemplateMiddleOrTemplateTail)); - // Element - case 231 /* Block */: - ts.Debug.type(node); - return ts.factory.updateBlock(node, visitList(node.statements, ts.isStatement)); - case 233 /* VariableStatement */: - ts.Debug.type(node); - return ts.factory.updateVariableStatement(node, visitList(node.modifiers, ts.isModifier), visit(node.declarationList, ts.isVariableDeclarationList)); - case 234 /* ExpressionStatement */: - ts.Debug.type(node); - return ts.factory.updateExpressionStatement(node, visitExpression(node.expression)); - case 235 /* IfStatement */: - ts.Debug.type(node); - return ts.factory.updateIfStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.thenStatement), visitEmbeddedStatement(node.elseStatement)); - case 236 /* DoStatement */: - ts.Debug.type(node); - return ts.factory.updateDoStatement(node, visitEmbeddedStatement(node.statement), visitExpression(node.expression)); - case 237 /* WhileStatement */: - ts.Debug.type(node); - return ts.factory.updateWhileStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 238 /* ForStatement */: - ts.Debug.type(node); - return ts.factory.updateForStatement(node, visitForInitializer(node.initializer), visitExpression(node.condition), visitExpression(node.incrementor), visitEmbeddedStatement(node.statement)); - case 239 /* ForInStatement */: - ts.Debug.type(node); - return ts.factory.updateForInStatement(node, visitForInitializer(node.initializer), visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 240 /* ForOfStatement */: - ts.Debug.type(node); - return ts.factory.updateForOfStatement(node, visit(node.awaitModifier, ts.isAwaitKeyword), visitForInitializer(node.initializer), visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 241 /* ContinueStatement */: - ts.Debug.type(node); - return ts.factory.updateContinueStatement(node, visitIdentifierName(node.label)); - case 242 /* BreakStatement */: - ts.Debug.type(node); - return ts.factory.updateBreakStatement(node, visitIdentifierName(node.label)); - case 243 /* ReturnStatement */: - ts.Debug.type(node); - return ts.factory.updateReturnStatement(node, visitExpression(node.expression)); - case 244 /* WithStatement */: - ts.Debug.type(node); - return ts.factory.updateWithStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 245 /* SwitchStatement */: - ts.Debug.type(node); - return ts.factory.updateSwitchStatement(node, visitExpression(node.expression), visit(node.caseBlock, ts.isCaseBlock)); - case 246 /* LabeledStatement */: - ts.Debug.type(node); - return ts.factory.updateLabeledStatement(node, visitIdentifierName(node.label), visitEmbeddedStatement(node.statement)); - case 247 /* ThrowStatement */: - ts.Debug.type(node); - return ts.factory.updateThrowStatement(node, visitExpression(node.expression)); - case 248 /* TryStatement */: - ts.Debug.type(node); - return ts.factory.updateTryStatement(node, visit(node.tryBlock, ts.isBlock), visit(node.catchClause, ts.isCatchClause), visit(node.finallyBlock, ts.isBlock)); - // Declarations - case 250 /* VariableDeclaration */: - ts.Debug.type(node); - return ts.factory.updateVariableDeclaration(node, visitBindingName(node.name), visit(node.exclamationToken, ts.isExclamationToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 251 /* VariableDeclarationList */: - ts.Debug.type(node); - return ts.factory.updateVariableDeclarationList(node, visitList(node.declarations, ts.isVariableDeclaration)); - case 252 /* FunctionDeclaration */: - ts.Debug.type(node); - return ts.factory.updateFunctionDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 253 /* ClassDeclaration */: - ts.Debug.type(node); - return ts.factory.updateClassDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isClassElement)); - case 254 /* InterfaceDeclaration */: - ts.Debug.type(node); - return ts.factory.updateInterfaceDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isTypeElement)); - case 255 /* TypeAliasDeclaration */: - ts.Debug.type(node); - return ts.factory.updateTypeAliasDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitTypeNode(node.type)); - case 256 /* EnumDeclaration */: - ts.Debug.type(node); - return ts.factory.updateEnumDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.members, ts.isEnumMember)); - case 257 /* ModuleDeclaration */: - ts.Debug.type(node); - return ts.factory.updateModuleDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitModuleName(node.name), visit(node.body, ts.isModuleBody)); - case 258 /* ModuleBlock */: - ts.Debug.type(node); - return ts.factory.updateModuleBlock(node, visitList(node.statements, ts.isStatement)); - case 259 /* CaseBlock */: - ts.Debug.type(node); - return ts.factory.updateCaseBlock(node, visitList(node.clauses, ts.isCaseOrDefaultClause)); - case 260 /* NamespaceExportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateNamespaceExportDeclaration(node, visitIdentifierName(node.name)); - case 261 /* ImportEqualsDeclaration */: - ts.Debug.type(node); - return ts.factory.updateImportEqualsDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), node.isTypeOnly, visitIdentifierName(node.name), visit(node.moduleReference, ts.isModuleReference)); - case 262 /* ImportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateImportDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.importClause, ts.isImportClause), visitExpression(node.moduleSpecifier)); - case 263 /* ImportClause */: - ts.Debug.type(node); - return ts.factory.updateImportClause(node, node.isTypeOnly, visitIdentifierName(node.name), visit(node.namedBindings, ts.isNamedImportBindings)); - case 264 /* NamespaceImport */: - ts.Debug.type(node); - return ts.factory.updateNamespaceImport(node, visitIdentifierName(node.name)); - case 270 /* NamespaceExport */: - ts.Debug.type(node); - return ts.factory.updateNamespaceExport(node, visitIdentifierName(node.name)); - case 265 /* NamedImports */: - ts.Debug.type(node); - return ts.factory.updateNamedImports(node, visitList(node.elements, ts.isImportSpecifier)); - case 266 /* ImportSpecifier */: - ts.Debug.type(node); - return ts.factory.updateImportSpecifier(node, visitIdentifierName(node.propertyName), visitIdentifierName(node.name)); - case 267 /* ExportAssignment */: - ts.Debug.type(node); - return ts.factory.updateExportAssignment(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitExpression(node.expression)); - case 268 /* ExportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateExportDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), node.isTypeOnly, visit(node.exportClause, ts.isNamedExportBindings), visitExpression(node.moduleSpecifier)); - case 269 /* NamedExports */: - ts.Debug.type(node); - return ts.factory.updateNamedExports(node, visitList(node.elements, ts.isExportSpecifier)); - case 271 /* ExportSpecifier */: - ts.Debug.type(node); - return ts.factory.updateExportSpecifier(node, visitIdentifierName(node.propertyName), visitIdentifierName(node.name)); - case 272 /* MissingDeclaration */: - return node; - // Module references - case 273 /* ExternalModuleReference */: - ts.Debug.type(node); - return ts.factory.updateExternalModuleReference(node, visitExpression(node.expression)); - // JSX (non-expression) - case 276 /* JsxOpeningElement */: - ts.Debug.type(node); - return ts.factory.updateJsxOpeningElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression), visitList(node.typeArguments, ts.isTypeNode), visit(node.attributes, ts.isJsxAttributes)); - case 277 /* JsxClosingElement */: - ts.Debug.type(node); - return ts.factory.updateJsxClosingElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression)); - case 281 /* JsxAttribute */: - ts.Debug.type(node); - return ts.factory.updateJsxAttribute(node, visitIdentifierName(node.name), visitJsxAttributeValue(node.initializer)); - case 282 /* JsxAttributes */: - ts.Debug.type(node); - return ts.factory.updateJsxAttributes(node, visitList(node.properties, ts.isJsxAttributeLike)); - case 283 /* JsxSpreadAttribute */: - ts.Debug.type(node); - return ts.factory.updateJsxSpreadAttribute(node, visitExpression(node.expression)); - case 284 /* JsxExpression */: - ts.Debug.type(node); - return ts.factory.updateJsxExpression(node, visitExpression(node.expression)); - // Clauses - case 285 /* CaseClause */: - ts.Debug.type(node); - return ts.factory.updateCaseClause(node, visitExpression(node.expression), visitList(node.statements, ts.isStatement)); - case 286 /* DefaultClause */: - ts.Debug.type(node); - return ts.factory.updateDefaultClause(node, visitList(node.statements, ts.isStatement)); - case 287 /* HeritageClause */: - ts.Debug.type(node); - return ts.factory.updateHeritageClause(node, visitList(node.types, ts.isExpressionWithTypeArguments)); - case 288 /* CatchClause */: - ts.Debug.type(node); - return ts.factory.updateCatchClause(node, visit(node.variableDeclaration, ts.isVariableDeclaration), visit(node.block, ts.isBlock)); - // Property assignments - case 289 /* PropertyAssignment */: - ts.Debug.type(node); - return ts.factory.updatePropertyAssignment(node, visitPropertyName(node.name), visitExpression(node.initializer)); - case 290 /* ShorthandPropertyAssignment */: - ts.Debug.type(node); - return ts.factory.updateShorthandPropertyAssignment(node, visitIdentifierName(node.name, ts.isIdentifier), visitExpression(node.objectAssignmentInitializer)); - case 291 /* SpreadAssignment */: - ts.Debug.type(node); - return ts.factory.updateSpreadAssignment(node, visitExpression(node.expression)); - // Enum - case 292 /* EnumMember */: - ts.Debug.type(node); - return ts.factory.updateEnumMember(node, visitPropertyName(node.name), visitExpression(node.initializer)); - // JSDoc nodes (only used in codefixes currently) - case 302 /* JSDocTypeExpression */: - case 303 /* JSDocNameReference */: - case 304 /* JSDocAllType */: - case 305 /* JSDocUnknownType */: - case 306 /* JSDocNullableType */: - case 307 /* JSDocNonNullableType */: - case 308 /* JSDocOptionalType */: - case 309 /* JSDocFunctionType */: - case 310 /* JSDocVariadicType */: - case 311 /* JSDocNamepathType */: - case 312 /* JSDocComment */: - case 314 /* JSDocTypeLiteral */: - case 315 /* JSDocSignature */: - case 317 /* JSDocTag */: - case 318 /* JSDocAugmentsTag */: - case 319 /* JSDocImplementsTag */: - case 320 /* JSDocAuthorTag */: - case 321 /* JSDocDeprecatedTag */: - case 322 /* JSDocClassTag */: - case 323 /* JSDocPublicTag */: - case 324 /* JSDocPrivateTag */: - case 325 /* JSDocProtectedTag */: - case 326 /* JSDocReadonlyTag */: - case 328 /* JSDocCallbackTag */: - case 329 /* JSDocEnumTag */: - case 330 /* JSDocParameterTag */: - case 337 /* JSDocPropertyTag */: - case 331 /* JSDocReturnTag */: - case 332 /* JSDocThisTag */: - case 333 /* JSDocTypeTag */: - case 334 /* JSDocTemplateTag */: - case 335 /* JSDocTypedefTag */: - case 336 /* JSDocSeeTag */: - return node; - // Transformation nodes (ignored) - } - if (ts.isExpression(node)) { - // If this was an expression that was originally in an `Unspecified` hint, - // re-trigger substitution using the correct hint. - hint = 1 /* Expression */; - if (substituteNode !== ts.noEmitSubstitution) { - node = substituteNode(hint, node); - } - } - else if (ts.isSourceFile(node)) { - return preprintSourceFile(node); - } - } - if (hint === 1 /* Expression */) { - switch (node.kind) { - // Identifiers - case 78 /* Identifier */: - return preprintIdentifier(node); - // Expression - case 200 /* ArrayLiteralExpression */: - ts.Debug.type(node); - return ts.factory.updateArrayLiteralExpression(node, visitExpressionList(node.elements)); - case 201 /* ObjectLiteralExpression */: - ts.Debug.type(node); - return ts.factory.updateObjectLiteralExpression(node, visitList(node.properties, ts.isObjectLiteralElementLike)); - case 202 /* PropertyAccessExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updatePropertyAccessChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitMemberName(node.name)); - } - ts.Debug.type(node); - return ts.factory.updatePropertyAccessExpression(node, visitExpression(node.expression), visitMemberName(node.name)); - case 203 /* ElementAccessExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateElementAccessChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitExpression(node.argumentExpression)); - } - ts.Debug.type(node); - return ts.factory.updateElementAccessExpression(node, visitExpression(node.expression), visitExpression(node.argumentExpression)); - case 204 /* CallExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateCallChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - } - ts.Debug.type(node); - return ts.factory.updateCallExpression(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - case 205 /* NewExpression */: - ts.Debug.type(node); - return ts.factory.updateNewExpression(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - case 206 /* TaggedTemplateExpression */: - ts.Debug.type(node); - return ts.factory.updateTaggedTemplateExpression(node, visitExpression(node.tag), visitTypeNodeList(node.typeArguments), visitExpression(node.template, ts.isTemplateLiteral)); - case 207 /* TypeAssertionExpression */: - ts.Debug.type(node); - return ts.factory.updateTypeAssertion(node, visitTypeNode(node.type), visitExpression(node.expression)); - case 208 /* ParenthesizedExpression */: - ts.Debug.type(node); - return ts.factory.updateParenthesizedExpression(node, visitExpression(node.expression)); - case 209 /* FunctionExpression */: - ts.Debug.type(node); - return ts.factory.updateFunctionExpression(node, visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 210 /* ArrowFunction */: - ts.Debug.type(node); - return ts.factory.updateArrowFunction(node, visitList(node.modifiers, ts.isModifier), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visit(node.equalsGreaterThanToken, ts.isEqualsGreaterThanToken), visitConciseBody(node.body)); - case 211 /* DeleteExpression */: - ts.Debug.type(node); - return ts.factory.updateDeleteExpression(node, visitExpression(node.expression)); - case 212 /* TypeOfExpression */: - ts.Debug.type(node); - return ts.factory.updateTypeOfExpression(node, visitExpression(node.expression)); - case 213 /* VoidExpression */: - ts.Debug.type(node); - return ts.factory.updateVoidExpression(node, visitExpression(node.expression)); - case 214 /* AwaitExpression */: - ts.Debug.type(node); - return ts.factory.updateAwaitExpression(node, visitExpression(node.expression)); - case 215 /* PrefixUnaryExpression */: - ts.Debug.type(node); - return ts.factory.updatePrefixUnaryExpression(node, visitExpression(node.operand)); - case 216 /* PostfixUnaryExpression */: - ts.Debug.type(node); - return ts.factory.updatePostfixUnaryExpression(node, visitExpression(node.operand)); - case 217 /* BinaryExpression */: - return preprintBinaryExpression(node); - case 218 /* ConditionalExpression */: - ts.Debug.type(node); - return ts.factory.updateConditionalExpression(node, visitExpression(node.condition), visit(node.questionToken, ts.isQuestionToken), visitExpression(node.whenTrue), visit(node.colonToken, ts.isColonToken), visitExpression(node.whenFalse)); - case 219 /* TemplateExpression */: - ts.Debug.type(node); - return ts.factory.updateTemplateExpression(node, visit(node.head, ts.isTemplateHead), visitList(node.templateSpans, ts.isTemplateSpan)); - case 220 /* YieldExpression */: - ts.Debug.type(node); - return ts.factory.updateYieldExpression(node, visit(node.asteriskToken, ts.isAsteriskToken), visitExpression(node.expression)); - case 221 /* SpreadElement */: - ts.Debug.type(node); - return ts.factory.updateSpreadElement(node, visitExpression(node.expression)); - case 222 /* ClassExpression */: - ts.Debug.type(node); - return ts.factory.updateClassExpression(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isClassElement)); - case 225 /* AsExpression */: - ts.Debug.type(node); - return ts.factory.updateAsExpression(node, visitExpression(node.expression), visitTypeNode(node.type)); - case 226 /* NonNullExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateNonNullChain(node, visitExpression(node.expression)); - } - ts.Debug.type(node); - return ts.factory.updateNonNullExpression(node, visitExpression(node.expression)); - case 227 /* MetaProperty */: - ts.Debug.type(node); - return ts.factory.updateMetaProperty(node, visitIdentifierName(node.name)); - // JSX (expression only) - case 274 /* JsxElement */: - ts.Debug.type(node); - return ts.factory.updateJsxElement(node, visit(node.openingElement, ts.isJsxOpeningElement), visitList(node.children, ts.isJsxChild), visit(node.closingElement, ts.isJsxClosingElement)); - case 275 /* JsxSelfClosingElement */: - ts.Debug.type(node); - return ts.factory.updateJsxSelfClosingElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression), visitList(node.typeArguments, ts.isTypeNode), visit(node.attributes, ts.isJsxAttributes)); - case 278 /* JsxFragment */: - ts.Debug.type(node); - return ts.factory.updateJsxFragment(node, visit(node.openingFragment, ts.isJsxOpeningFragment), visitList(node.children, ts.isJsxChild), visit(node.closingFragment, ts.isJsxClosingFragment)); - // Transformation nodes - case 340 /* PartiallyEmittedExpression */: - ts.Debug.type(node); - return ts.factory.updatePartiallyEmittedExpression(node, visitExpression(node.expression)); - case 341 /* CommaListExpression */: - ts.Debug.type(node); - return ts.factory.updateCommaListExpression(node, visitExpressionList(node.elements, ts.isExpression)); - } - } - if (ts.Debug.shouldAssert(1 /* Normal */)) { - // Any other node should not have children or this list isn't up to date. - ts.Debug.assertMissingNode(ts.forEachChild(node, ts.identity), "Expected " + ts.Debug.formatSyntaxKind(node.kind) + " to contain no children."); - } - // No need to visit nodes with no children. - return node; - } - function preprintSourceFile(node) { - return ts.factory.updateSourceFile(node, visitList(node.statements, ts.isStatement)); - } - function preprintIdentifier(node) { - return ts.factory.updateIdentifier(node, visitList(node.typeArguments, ts.isTypeNodeOrTypeParameterDeclaration)); - } - function preprintTypeParameterDeclaration(node) { - return ts.factory.updateTypeParameterDeclaration(node, visitIdentifierName(node.name), visitTypeNode(node.constraint), visitTypeNode(node.default)); - } - function createPreprintBinaryExpression() { - return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); - function onEnter(node, state) { - if (state) { - state.stackIndex++; - state.leftStack[state.stackIndex] = node.left; - state.operatorStack[state.stackIndex] = node.operatorToken; - state.rightStack[state.stackIndex] = node.right; - } - else { - state = { - stackIndex: 0, - leftStack: [node.left], - operatorStack: [node.operatorToken], - rightStack: [node.right], - }; - } - return state; - } - function onLeft(left, state, _node) { - return maybeVisitExpression(left, state, "left"); - } - function onOperator(operator, state, _node) { - state.operatorStack[state.stackIndex] = visit(operator, ts.isBinaryOperatorToken); - } - function onRight(right, state, _node) { - return maybeVisitExpression(right, state, "right"); - } - function onExit(node, state) { - var left = state.leftStack[state.stackIndex]; - var operator = state.operatorStack[state.stackIndex]; - var right = state.rightStack[state.stackIndex]; - if (state.stackIndex > 0) { - state.stackIndex--; - } - return ts.factory.updateBinaryExpression(node, left, operator, right); - } - function foldState(state, result, side) { - (side === "left" ? state.leftStack : state.rightStack)[state.stackIndex] = result; - return state; - } - function maybeVisitExpression(node, state, side) { - // Get the first supported pipeline phase for this node. We can skip several stack - // frames if we aren't doing emit notification, so we check for substitution and - // direct callbacks and execute those immediately. - var pipelinePhase = getPipelinePhase(0 /* Notification */, node); - if (pipelinePhase === pipelineVisitWithSubstitution) { - // The next phase after substitution is always direct visitation, so we can reduce the call stack - // depth by proceding to the direct visitor. - node = ts.cast(substituteNode(1 /* Expression */, node), ts.isExpression); - pipelinePhase = pipelineVisitDirect; - } - if (pipelinePhase === pipelineVisitDirect && ts.isBinaryExpression(node)) { - // If we are visiting directly and the next node is a BinaryExpression, we can - // add it to the stack and continue the trampoline. - return node; - } - else { - // Visit the expression and store the result on whichever side we are currently visiting. - (side === "left" ? state.leftStack : state.rightStack)[state.stackIndex] = visitExpression(node, ts.isExpression); - } - } - } - var preprintBinaryExpression = createPreprintBinaryExpression(); - function preprint(hint, node) { - // If we're not performing substitution or notification, we have no work to do here. - if (substituteNode === ts.noEmitSubstitution && - onEmitNode === ts.noEmitNotification) { - return node; - } - switch (hint) { - case 0 /* SourceFile */: return visitSourceFile(ts.cast(node, ts.isSourceFile)); - case 1 /* Expression */: return visitExpression(ts.cast(node, ts.isExpression)); - case 2 /* IdentifierName */: return visitIdentifierName(ts.cast(node, ts.isIdentifier)); - case 3 /* MappedTypeParameter */: return visitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 5 /* EmbeddedStatement */: return visitEmbeddedStatement(ts.cast(node, ts.isStatement)); - case 6 /* JsxAttributeValue */: return visitJsxAttributeValue(ts.cast(node, ts.isStringLiteralOrJsxExpression)); - default: return visit(node); - } - } - return preprint; - } function createBracketsMap() { var brackets = []; brackets[1024 /* Braces */] = ["{", "}"]; @@ -109434,6 +109370,7 @@ var ts; var hasEmitBlockingDiagnostics = new ts.Map(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; + var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { @@ -109448,7 +109385,7 @@ var ts; }); }; } else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } @@ -109457,7 +109394,8 @@ var ts; actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { - var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; // TODO: GH#18217 actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -109614,6 +109552,7 @@ var ts; } }); } + typeReferenceDirectiveResolutionCache = undefined; // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; var program = { @@ -109807,13 +109746,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_15 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_14.push(resolvedModule); + result_15.push(resolvedModule); } - return result_14; + return result_15; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -111245,12 +111184,14 @@ var ts; return host.getCanonicalFileName(fileName); } function processImportedModules(file) { + var _a; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var resolutions = resolveModuleNamesReusingOldState(moduleNames, file); ts.Debug.assert(resolutions.length === moduleNames.length); + var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options; for (var index = 0; index < moduleNames.length; index++) { var resolution = resolutions[index]; ts.setResolvedModule(file, moduleNames[index], resolution); @@ -111273,11 +111214,11 @@ var ts; // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !ts.getAllowJSCompilerOption(options)) + && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile)) && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -112365,7 +112306,7 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos: fileInfos, @@ -113165,7 +113106,16 @@ var ts; var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - return signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; + var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); var referencedMap; if (state.referencedMap) { @@ -113214,7 +113164,7 @@ var ts; return { fileNames: fileNames, fileInfos: fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, @@ -113246,17 +113196,16 @@ var ts; return fileIdListId; } } - function convertToReusableCompilerOptions(options, relativeToBuildInfo) { - var result = {}; + function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { + var result; var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo); + 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.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { @@ -113572,6 +113521,14 @@ var ts; state.affectedFilesPendingEmitIndex = 0; } } + function toBuilderStateFileInfo(fileInfo) { + return ts.isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + ts.isString(fileInfo.signature) ? + fileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; + } + ts.toBuilderStateFileInfo = toBuilderStateFileInfo; function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { var _a; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); @@ -113579,10 +113536,10 @@ var ts; 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), fileInfo); }); + program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); var state = { fileInfos: fileInfos, - compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, referencedMap: toMapOfReferencedSet(program.referencedMap), exportedModulesMap: toMapOfReferencedSet(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]; }), @@ -113742,9 +113699,9 @@ var ts; var resolutionsWithFailedLookups = []; var resolvedFileToResolution = ts.createMultiMap(); var hasChangedAutomaticTypeDirectiveNames = false; - var failedLookupChecks = []; - var startsWithPathChecks = []; - var isInDirectoryChecks = []; + var failedLookupChecks; + var startsWithPathChecks; + var isInDirectoryChecks; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -113753,9 +113710,12 @@ var ts; var resolvedModuleNames = new ts.Map(); var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache); var resolvedTypeReferenceDirectives = new ts.Map(); var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -113813,9 +113773,9 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.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(); @@ -113851,9 +113811,8 @@ var ts; isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -113880,7 +113839,7 @@ 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), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; @@ -113891,6 +113850,9 @@ var ts; // Default return the result from the first pass return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } function resolveNamesWithLocalCache(_a) { var _b; var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; @@ -113978,7 +113940,7 @@ var ts; redirectedReference: redirectedReference, cache: resolvedTypeReferenceDirectives, perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, - loader: ts.resolveTypeReferenceDirective, + loader: resolveTypeReferenceDirective, getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, }); @@ -114253,7 +114215,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -114271,8 +114233,8 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -114283,27 +114245,33 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(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. + var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { return resolution.failedLookupLocations.some(function (location) { var locationPath = resolutionHost.toPath(location); return ts.contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) || - isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, 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); })); }); } function closeTypeRootsWatch() { @@ -114524,7 +114492,7 @@ var ts; if (!baseUrl && !paths || relativePreference === 0 /* Relative */) { return relativePath; } - var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl; + var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -114539,7 +114507,9 @@ var ts; return nonRelative; } if (relativePreference === 3 /* ExternalNonRelative */) { - var projectDirectory = host.getCurrentDirectory(); + var projectDirectory = compilerOptions.configFilePath ? + ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName); var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory); var targetIsInternal = ts.startsWith(modulePath, projectDirectory); @@ -114614,9 +114584,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 links = host.getSymlinkCache ? host.getSymlinkCache() @@ -114639,10 +114609,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; } }); }); @@ -114773,7 +114743,7 @@ var ts; ts.startsWith(relativeToBaseUrl, prefix) && ts.endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } @@ -116374,12 +116344,19 @@ var ts; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); 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) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } + if (!compilerHost.resolveTypeReferenceDirectives) { + var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4); + }; + } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -116404,6 +116381,7 @@ var ts; projectErrorsReported: new ts.Map(), compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, + typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, // Mutable state buildOrder: undefined, readFileWithCache: function (f) { return host.readFile(f); }, @@ -116591,7 +116569,7 @@ var ts; function disableCache(state) { if (!state.cache) return; - var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache; + var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -116600,10 +116578,8 @@ var ts; compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear(); state.cache = undefined; } function clearProjectStatus(state, resolved) { @@ -116770,6 +116746,7 @@ var ts; return withProgramOrUndefined(action) || ts.emptyArray; } function createProgram() { + var _a, _b; ts.Debug.assert(program === undefined); if (state.options.dry) { reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -116789,7 +116766,8 @@ var ts; var host = state.host, compilerHost = state.compilerHost; state.projectCompilerOptions = config.options; // Update module resolution cache if needed - updateModuleResolutionCache(state, project, config); + (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { @@ -116964,7 +116942,7 @@ var ts; emitBundle(writeFile, customTransformers); break; case BuildStep.BuildInvalidatedProjectOfBundle: - ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; case BuildStep.QueueReferencingProjects: @@ -117106,31 +117084,6 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache(state, proj, config) { - if (!state.moduleResolutionCache) - return; - // Update module resolution cache if needed - var moduleResolutionCache = state.moduleResolutionCache; - var projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - // The own map will be for projectCompilerOptions - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - // Set correct own map - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - var ref = { - sourceFile: config.options.configFile, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time var tsconfigTime = ts.getModifiedTime(state.host, configFile); @@ -117143,6 +117096,7 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { + var force = !!state.options.force; var newestInputFileName = undefined; var newestInputFileTime = minimumDate; var host = state.host; @@ -117155,11 +117109,13 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = ts.getModifiedTime(host, inputFile); - host.getModifiedTime(inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + var inputTime = ts.getModifiedTime(host, inputFile); + host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } // Container if no files are specified in the project @@ -117178,36 +117134,38 @@ var ts; var missingOutputFileName; var newestDeclarationFileContentChangedTime = minimumDate; var isOutOfDateWithInputs = false; - 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 (isDeclarationFile(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + 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 (isDeclarationFile(output)) { + var outputModifiedTime = ts.getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } var pseudoUpToDate = false; @@ -117243,7 +117201,8 @@ var ts; }; } // Check oldest output file name only if there is no missing output file name - if (!missingOutputFileName) { + // (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) { @@ -117289,7 +117248,7 @@ var ts; if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -117431,7 +117390,7 @@ var ts; } } } - function build(state, project, cancellationToken, onlyReferences) { + function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -117443,7 +117402,7 @@ var ts; if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -117625,9 +117584,9 @@ var ts; function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: function (project, cancellationToken) { return build(state, project, cancellationToken); }, + build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); }, clean: function (project) { return clean(state, project); }, - buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); }, + buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, /*onlyReferences*/ true); }, cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); }, getNextInvalidatedProject: function (cancellationToken) { setupInitialBuild(state, cancellationToken); @@ -117717,6 +117676,9 @@ 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)); @@ -118856,7 +118818,7 @@ var ts; case 167 /* Constructor */: return "constructor" /* constructorImplementationElement */; case 160 /* TypeParameter */: return "type parameter" /* typeParameterElement */; case 292 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 161 /* Parameter */: return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 161 /* Parameter */: return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; case 261 /* ImportEqualsDeclaration */: case 266 /* ImportSpecifier */: case 271 /* ExportSpecifier */: @@ -119540,6 +119502,21 @@ var ts; return current; } } + /** + * Returns the first token where position is in [start, end), + * excluding `JsxText` tokens containing only whitespace. + */ + function findFirstNonJsxWhitespaceToken(sourceFile, position) { + var tokenAtPosition = getTokenAtPosition(sourceFile, position); + while (isWhiteSpaceOnlyJsxText(tokenAtPosition)) { + var nextToken = findNextToken(tokenAtPosition, tokenAtPosition.parent, sourceFile); + if (!nextToken) + return; + tokenAtPosition = nextToken; + } + return tokenAtPosition; + } + ts.findFirstNonJsxWhitespaceToken = findFirstNonJsxWhitespaceToken; /** * The token on the left of the position is the token that strictly includes the position * or sits to the left of the cursor if it is on a boundary. For example @@ -120534,6 +120511,14 @@ var ts; return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); } ts.operatorPart = operatorPart; + function parameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.parameterName); + } + ts.parameterNamePart = parameterNamePart; + function propertyNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.propertyName); + } + ts.propertyNamePart = propertyNamePart; function textOrKeywordPart(text) { var kind = ts.stringToToken(text); return kind === undefined @@ -120545,6 +120530,14 @@ var ts; return displayPart(text, ts.SymbolDisplayPartKind.text); } ts.textPart = textPart; + function typeAliasNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.aliasName); + } + ts.typeAliasNamePart = typeAliasNamePart; + function typeParameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.typeParameterName); + } + ts.typeParameterNamePart = typeParameterNamePart; function linkTextPart(text) { return displayPart(text, ts.SymbolDisplayPartKind.linkText); } @@ -120565,6 +120558,7 @@ var ts; } ts.linkPart = linkPart; function buildLinkParts(link, checker) { + var _a; var parts = [linkPart("{@link ")]; if (!link.name) { if (link.text) { @@ -120573,8 +120567,9 @@ var ts; } else { var symbol = checker === null || checker === void 0 ? void 0 : checker.getSymbolAtLocation(link.name); - if (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) { - parts.push(linkNamePart(link.name, symbol.valueDeclaration)); + var decl = (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) || ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]); + if (decl) { + parts.push(linkNamePart(link.name, decl)); if (link.text) { parts.push(linkTextPart(link.text)); } @@ -123854,6 +123849,7 @@ var ts; sourceDisplay: sourceDisplay, isSnippet: isSnippet, isPackageJsonImport: originIsPackageJsonImport(origin) || undefined, + isImportStatementCompletion: originIsResolvedExport(origin) || undefined, data: data, }; } @@ -124655,7 +124651,8 @@ var ts; return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined; } function tryGetGlobalSymbols() { - var result = tryGetObjectLikeCompletionSymbols() + var result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() + || tryGetObjectLikeCompletionSymbols() || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() @@ -124800,8 +124797,9 @@ var ts; } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 111 /* TypeOfKeyword */ && - (contextToken.parent.kind === 177 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + ((contextToken.kind === 111 /* TypeOfKeyword */ && + (contextToken.parent.kind === 177 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent))) || + (contextToken.kind === 127 /* AssertsKeyword */ && contextToken.parent.kind === 173 /* TypePredicate */)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { @@ -125018,6 +125016,25 @@ var ts; return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) || position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken))); } + function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() { + var typeLiteralNode = tryGetTypeLiteralNode(contextToken); + if (!typeLiteralNode) + return 0 /* Continue */; + var intersectionTypeNode = ts.isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : undefined; + var containerTypeNode = intersectionTypeNode || typeLiteralNode; + var containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker); + if (!containerExpectedType) + return 0 /* Continue */; + var containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode); + var members = getPropertiesForCompletion(containerExpectedType, typeChecker); + var existingMembers = getPropertiesForCompletion(containerActualType, typeChecker); + var existingMemberEscapedNames = new ts.Set(); + existingMembers.forEach(function (s) { return existingMemberEscapedNames.add(s.escapedName); }); + symbols = ts.filter(members, function (s) { return !existingMemberEscapedNames.has(s.escapedName); }); + completionKind = 0 /* ObjectPropertyDeclaration */; + isNewIdentifierLocation = true; + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in object literals and object binding patterns. * Relevant symbols are stored in the captured 'symbols' variable. @@ -125402,7 +125419,7 @@ var ts; case 41 /* AsteriskToken */: return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } - // If the previous token is keyword correspoding to class member completion keyword + // If the previous token is keyword corresponding to class member completion keyword // there will be completion available here if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; @@ -125437,6 +125454,31 @@ var ts; case 129 /* AsyncKeyword */: return ts.isPropertyDeclaration(contextToken.parent); } + // If we are inside a class declaration, and `constructor` is totally not present, + // but we request a completion manually at a whitespace... + var ancestorClassLike = ts.findAncestor(contextToken.parent, ts.isClassLike); + if (ancestorClassLike && contextToken === previousToken && isPreviousPropertyDeclarationTerminated(contextToken, position)) { + return false; // Don't block completions. + } + var ancestorPropertyDeclaraion = ts.getAncestor(contextToken.parent, 164 /* PropertyDeclaration */); + // If we are inside a class declaration and typing `constructor` after property declaration... + if (ancestorPropertyDeclaraion + && contextToken !== previousToken + && ts.isClassLike(previousToken.parent.parent) + // And the cursor is at the token... + && position <= previousToken.end) { + // If we are sure that the previous property declaration is terminated according to newline or semicolon... + if (isPreviousPropertyDeclarationTerminated(contextToken, previousToken.end)) { + return false; // Don't block completions. + } + else if (contextToken.kind !== 62 /* EqualsToken */ + // Should not block: `class C { blah = c/**/ }` + // But should block: `class C { blah = somewhat c/**/ }` and `class C { blah: SomeType c/**/ }` + && (ts.isInitializedProperty(ancestorPropertyDeclaraion) + || ts.hasType(ancestorPropertyDeclaraion))) { + return true; + } + } return ts.isDeclarationName(contextToken) && !ts.isShorthandPropertyAssignment(contextToken.parent) && !ts.isJsxAttribute(contextToken.parent) @@ -125444,6 +125486,11 @@ var ts; // If `contextToken !== previousToken`, this is `class C ex/**/`. && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } + function isPreviousPropertyDeclarationTerminated(contextToken, position) { + return contextToken.kind !== 62 /* EqualsToken */ && + (contextToken.kind === 26 /* SemicolonToken */ + || !ts.positionsAreOnSameLine(contextToken.end, position, sourceFile)); + } function isFunctionLikeButNotConstructor(kind) { return ts.isFunctionLikeKind(kind) && kind !== 167 /* Constructor */; } @@ -125849,6 +125896,12 @@ var ts; } if (!contextToken) return undefined; + // class C { blah; constructor/**/ } and so on + if (location.kind === 132 /* ConstructorKeyword */ + // class C { blah \n constructor/**/ } + || (ts.isIdentifier(contextToken) && ts.isPropertyDeclaration(contextToken.parent) && ts.isClassLike(location))) { + return ts.findAncestor(contextToken, ts.isClassLike); + } switch (contextToken.kind) { case 62 /* EqualsToken */: return undefined; @@ -125874,6 +125927,44 @@ var ts; ? contextToken.parent.parent : undefined; } } + function tryGetTypeLiteralNode(node) { + if (!node) + return undefined; + var parent = node.parent; + switch (node.kind) { + case 18 /* OpenBraceToken */: + if (ts.isTypeLiteralNode(parent)) { + return parent; + } + break; + case 26 /* SemicolonToken */: + case 27 /* CommaToken */: + case 78 /* Identifier */: + if (parent.kind === 163 /* PropertySignature */ && ts.isTypeLiteralNode(parent.parent)) { + return parent.parent; + } + break; + } + return undefined; + } + function getConstraintOfTypeArgumentProperty(node, checker) { + if (!node) + return undefined; + if (ts.isTypeNode(node) && ts.isTypeReferenceType(node.parent)) { + return checker.getTypeArgumentConstraint(node); + } + var t = getConstraintOfTypeArgumentProperty(node.parent, checker); + if (!t) + return undefined; + switch (node.kind) { + case 163 /* PropertySignature */: + return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); + case 184 /* IntersectionType */: + case 178 /* TypeLiteral */: + case 183 /* UnionType */: + return t; + } + } // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes function isFromObjectTypeDeclaration(node) { return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); @@ -125933,7 +126024,8 @@ var ts; if (type) { return type; } - if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { + if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ && node === node.parent.left) { + // Object literal is assignment pattern: ({ | } = x) return typeChecker.getTypeAtLocation(node.parent); } return undefined; @@ -126434,6 +126526,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function isDocumentRegistryEntry(entry) { + return !!entry.sourceFile; + } function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); } @@ -126450,10 +126545,16 @@ var ts; var entries = buckets.get(name); var sourceFiles = []; entries.forEach(function (entry, name) { - sourceFiles.push({ - name: name, - refCount: entry.languageServiceRefCount - }); + if (isDocumentRegistryEntry(entry)) { + sourceFiles.push({ + name: name, + scriptKind: entry.sourceFile.scriptKind, + refCount: entry.languageServiceRefCount + }); + } + else { + entry.forEach(function (value, scriptKind) { return sourceFiles.push({ name: name, scriptKind: scriptKind, refCount: value.languageServiceRefCount }); }); + } }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); return { @@ -126479,10 +126580,17 @@ var ts; function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } + 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:" + scriptKind + " and sourceFile.scriptKind: " + (entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind) + ", !entry: " + !entry); + return entry; + } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); - var entry = bucket.get(path); + scriptKind = ts.ensureScriptKind(fileName, scriptKind); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; + var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -126491,7 +126599,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 0 }; - bucket.set(path, entry); + setBucketEntry(); } } if (!entry) { @@ -126504,7 +126612,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 1, }; - bucket.set(path, entry); + setBucketEntry(); } else { // We have an entry for this file. However, it may be for a different version of @@ -126527,25 +126635,49 @@ var ts; } ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; + function setBucketEntry() { + if (!bucketEntry) { + bucket.set(path, entry); + } + else if (isDocumentRegistryEntry(bucketEntry)) { + var scriptKindMap = new ts.Map(); + scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry); + scriptKindMap.set(scriptKind, entry); + bucket.set(path, scriptKindMap); + } + else { + bucketEntry.set(scriptKind, entry); + } + } } - function releaseDocument(fileName, compilationSettings) { + function releaseDocument(fileName, compilationSettings, scriptKind) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); + return releaseDocumentWithKey(path, key, scriptKind); } - function releaseDocumentWithKey(path, key) { + function releaseDocumentWithKey(path, key, scriptKind) { var bucket = ts.Debug.checkDefined(buckets.get(key)); - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.delete(path); + if (isDocumentRegistryEntry(bucketEntry)) { + bucket.delete(path); + } + else { + bucketEntry.delete(scriptKind); + if (bucketEntry.size === 1) { + bucket.set(path, ts.firstDefinedIterator(bucketEntry.values(), ts.identity)); + } + } } } - function getLanguageServiceRefCounts(path) { + function getLanguageServiceRefCounts(path, scriptKind) { return ts.arrayFrom(buckets.entries(), function (_a) { var key = _a[0], bucket = _a[1]; - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); return [key, entry && entry.languageServiceRefCount]; }); } @@ -126975,13 +127107,13 @@ var ts; function getExport() { var _a; var parent = node.parent; - var grandParent = parent.parent; + var grandparent = parent.parent; if (symbol.exportSymbol) { if (parent.kind === 202 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandParent) - ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandparent) + ? getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ false) : undefined; } else { @@ -127011,15 +127143,15 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(grandParent)) { - return getExportAssignmentExport(grandParent); + else if (ts.isExportAssignment(grandparent)) { + return getExportAssignmentExport(grandparent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(grandParent)) { - return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandparent)) { + return getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ true); } else if (ts.isJSDocTypedefTag(parent)) { return exportInfo(symbol, 0 /* Named */); @@ -127027,9 +127159,10 @@ var ts; } function getExportAssignmentExport(ex) { // Get the symbol for the `export =` node; its parent is the module it's the export of. - var exportingModuleSymbol = ts.Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + if (!ex.symbol.parent) + return undefined; var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; - return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: ex.symbol.parent, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; @@ -127981,9 +128114,9 @@ var ts; // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); } - else if (node && node.kind === 87 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */) { + else if (node && node.kind === 87 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) { addReference(node, symbol, state); - searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); @@ -128198,7 +128331,9 @@ var ts; for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { var node = _d[_c]; // Import specifiers should be handled by importSearches - if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + var symbol = checker.getSymbolAtLocation(node); + var hasExportAssignmentDeclaration = ts.some(symbol === null || symbol === void 0 ? void 0 : symbol.declarations, function (d) { return ts.tryCast(d, ts.isExportAssignment) ? true : false; }); + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) { cb(node); } } @@ -128505,6 +128640,10 @@ var ts; default: ts.Debug.assertNever(state.specialSearchKind); } + // Use the parent symbol if the location is commonjs require syntax on javascript files only. + referenceSymbol = ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 199 /* BindingElement */ && ts.isRequireVariableDeclaration(referenceLocation.parent) + ? referenceLocation.parent.symbol + : referenceSymbol; getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { @@ -128872,6 +129011,8 @@ var ts; case 166 /* MethodDeclaration */: case 165 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { + staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning object literals break; } // falls through @@ -128912,7 +129053,8 @@ var ts; return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; case 222 /* ClassExpression */: case 253 /* ClassDeclaration */: - // Make sure the container belongs to the same class + case 201 /* ObjectLiteralExpression */: + // Make sure the container belongs to the same class/object literals // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getSyntacticModifierFlags(container) & 32 /* Static */) === staticFlag; case 298 /* SourceFile */: @@ -130040,7 +130182,7 @@ var ts; end: node.getEnd(), fileName: node.text }, - unverified: !!verifiedFileName, + unverified: !verifiedFileName, }; } } @@ -130193,7 +130335,38 @@ var ts; var sourceFile = name.getSourceFile(); var textSpan = ts.createTextSpanFromNode(name, sourceFile); return __assign(__assign({ fileName: sourceFile.fileName, textSpan: textSpan, kind: symbolKind, name: symbolName, containerKind: undefined, // TODO: GH#18217 - containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !checker.isDeclarationVisible(declaration) }); + containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !isDefinitionVisible(checker, declaration) }); + } + function isDefinitionVisible(checker, declaration) { + if (checker.isDeclarationVisible(declaration)) + return true; + if (!declaration.parent) + return false; + // Variable initializers are visible if variable is visible + if (ts.hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) + return isDefinitionVisible(checker, declaration.parent); + // Handle some exceptions here like arrow function, members of class and object literal expression which are technically not visible but we want the definition to be determined by its parent + switch (declaration.kind) { + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + // Private/protected properties/methods are not visible + if (ts.hasEffectiveModifier(declaration, 8 /* Private */)) + return false; + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 167 /* Constructor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + return isDefinitionVisible(checker, declaration.parent); + default: + return false; + } } function createDefinitionFromSignatureDeclaration(typeChecker, decl) { return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); @@ -130286,6 +130459,7 @@ var ts; "kind", "lends", "license", + "link", "listens", "member", "memberof", @@ -130379,8 +130553,9 @@ var ts; return ts.flatMap(comment, function (node) { return node.kind === 313 /* JSDocText */ ? [ts.textPart(node.text)] : ts.buildLinkParts(node, checker); }); } function getCommentDisplayParts(tag, checker) { - var comment = tag.comment; - switch (tag.kind) { + var comment = tag.comment, kind = tag.kind; + var namePart = getTagNameDisplayPart(kind); + switch (kind) { case 319 /* JSDocImplementsTag */: return withNode(tag.class); case 318 /* JSDocAugmentsTag */: @@ -130395,7 +130570,9 @@ var ts; case 330 /* JSDocParameterTag */: case 336 /* JSDocSeeTag */: var name = tag.name; - return name ? withNode(name) : comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); + return name ? withNode(name) + : comment === undefined ? undefined + : getDisplayPartsFromComment(comment, checker); default: return comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); } @@ -130403,7 +130580,32 @@ var ts; return addComment(node.getText()); } function addComment(s) { - return comment ? __spreadArray([ts.textPart(s), ts.spacePart()], getDisplayPartsFromComment(comment, checker)) : [ts.textPart(s)]; + if (comment) { + if (s.match(/^https?$/)) { + return __spreadArray([ts.textPart(s)], getDisplayPartsFromComment(comment, checker)); + } + else { + return __spreadArray([namePart(s), ts.spacePart()], getDisplayPartsFromComment(comment, checker)); + } + } + else { + return [ts.textPart(s)]; + } + } + } + function getTagNameDisplayPart(kind) { + switch (kind) { + case 330 /* JSDocParameterTag */: + return ts.parameterNamePart; + case 337 /* JSDocPropertyTag */: + return ts.propertyNamePart; + case 334 /* JSDocTemplateTag */: + return ts.typeParameterNamePart; + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + return ts.typeAliasNamePart; + default: + return ts.textPart; } } function getJSDocTagNameCompletions() { @@ -131656,9 +131858,9 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences) { + function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); @@ -131693,26 +131895,35 @@ var ts; ? coalesce(importGroup) : importGroup; }); - // Delete or replace the first import. + // Delete all nodes if there are no imports. if (newImportDecls.length === 0) { - changeTracker.delete(sourceFile, oldImportDecls[0]); + // Consider the first node to have trailingTrivia as we want to exclude the + // "header" comment. + changeTracker.deleteNodes(sourceFile, oldImportDecls, { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, /*hasTrailingComment*/ true); } else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + var replaceOptions = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - // Delete any subsequent imports. - for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + }; + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions); + var hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions); + changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, hasTrailingComment); } } } OrganizeImports.organizeImports = organizeImports; - function removeUnusedImports(oldImports, sourceFile, program) { + function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { + // As a precaution, consider unused import detection to be destructive (GH #43051) + if (skipDestructiveCodeActions) { + return oldImports; + } var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); var jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile); @@ -133190,7 +133401,7 @@ var ts; function getRenameInfo(program, sourceFile, position, options) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); if (renameInfo) { return renameInfo; } @@ -133198,7 +133409,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -133218,7 +133429,7 @@ var ts; if (!declarations || declarations.length === 0) return; // Disallow rename for elements that are defined in the standard TypeScript library. - if (declarations.some(isDefinedInLibraryFile)) { + if (declarations.some(function (declaration) { return isDefinedInLibraryFile(program, declaration); })) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; @@ -133236,6 +133447,10 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), node, sourceFile); } + function isDefinedInLibraryFile(program, declaration) { + var sourceFile = declaration.getSourceFile(); + return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); @@ -134386,7 +134601,7 @@ var ts; diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } } - if (ts.isFunctionLikeDeclaration(node)) { + if (canBeConvertedToAsync(node)) { addConvertToAsyncFunctionDiagnostics(node, checker, diags); } node.forEachChild(check); @@ -134443,11 +134658,11 @@ var ts; returnsPromise(node, checker); } function returnsPromise(node, checker) { - var functionType = checker.getTypeAtLocation(node); - var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); - var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + var signature = checker.getSignatureFromDeclaration(node); + var returnType = signature ? checker.getReturnTypeOfSignature(signature) : undefined; return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } + ts.returnsPromise = returnsPromise; function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } @@ -134529,6 +134744,18 @@ var ts; } return false; } + function canBeConvertedToAsync(node) { + switch (node.kind) { + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + return true; + default: + return false; + } + } + ts.canBeConvertedToAsync = canBeConvertedToAsync; })(ts || (ts = {})); /* @internal */ var ts; @@ -134700,7 +134927,7 @@ var ts; symbolKind = "property" /* memberVariableElement */; } var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (location.parent && location.parent.kind === 202 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing @@ -138324,7 +138551,9 @@ var ts; function getAdjustedRange(sourceFile, startNode, endNode, options) { return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - function getAdjustedStartPosition(sourceFile, node, options) { + function getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment) { + var _a, _b; + if (hasTrailingComment === void 0) { hasTrailingComment = false; } var leadingTriviaOption = options.leadingTriviaOption; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); @@ -138355,6 +138584,15 @@ var ts; // when b is deleted - we delete it return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start; } + // if node has a trailing comments, use comment end position as the text has already been included. + if (hasTrailingComment) { + // Check first for leading comments as if the node is the first import, we want to exclude the trivia; + // otherwise we get the trailing comments. + var comment = ((_a = ts.getLeadingCommentRanges(sourceFile.text, fullStart)) === null || _a === void 0 ? void 0 : _a[0]) || ((_b = ts.getTrailingCommentRanges(sourceFile.text, fullStart)) === null || _b === void 0 ? void 0 : _b[0]); + if (comment) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } // get start position of the line following the line that contains fullstart position // (but only if the fullstart isn't the very beginning of the file) var nextLineStart = fullStart > 0 ? 1 : 0; @@ -138363,6 +138601,35 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } + /** Return the end position of a multiline comment of it is on another line; otherwise returns `undefined`; */ + function getEndPositionOfMultilineTrailingComment(sourceFile, node, options) { + var end = node.end; + var trailingTriviaOption = options.trailingTriviaOption; + if (trailingTriviaOption === TrailingTriviaOption.Include) { + // If the trailing comment is a multiline comment that extends to the next lines, + // return the end of the comment and track it for the next nodes to adjust. + var comments = ts.getTrailingCommentRanges(sourceFile.text, end); + if (comments) { + var nodeEndLine = ts.getLineOfLocalPosition(sourceFile, node.end); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + // Single line can break the loop as trivia will only be this line. + // Comments on subsequest lines are also ignored. + if (comment.kind === 2 /* SingleLineCommentTrivia */ || ts.getLineOfLocalPosition(sourceFile, comment.pos) > nodeEndLine) { + break; + } + // Get the end line of the comment and compare against the end line of the node. + // If the comment end line position and the multiline comment extends to multiple lines, + // then is safe to return the end position. + var commentEndLine = ts.getLineOfLocalPosition(sourceFile, comment.end); + if (commentEndLine > nodeEndLine) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } + } + } + return undefined; + } function getAdjustedEndPosition(sourceFile, node, options) { var _a; var end = node.end; @@ -138378,6 +138645,10 @@ var ts; } return end; } + var multilineEndPosition = getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + if (multilineEndPosition) { + return multilineEndPosition; + } var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd @@ -138389,13 +138660,6 @@ var ts; function isSeparator(node, candidate) { return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 201 /* ObjectLiteralExpression */)); } - function spaces(count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += " "; - } - return s; - } function isThisTypeAnnotatable(containingFunction) { return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction); } @@ -138440,6 +138704,17 @@ var ts; if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); }; + ChangeTracker.prototype.deleteNodes = function (sourceFile, nodes, options, hasTrailingComment) { + if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } + // When deleting multiple nodes we need to track if the end position is including multiline trailing comments. + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment); + var end = getAdjustedEndPosition(sourceFile, node, options); + this.deleteRange(sourceFile, { pos: pos, end: end }); + hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + } + }; ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; @@ -138482,6 +138757,10 @@ var ts; if (options === void 0) { options = useNonAdjustedPositions; } this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; + ChangeTracker.prototype.nodeHasTrailingComment = function (sourceFile, oldNode, configurableEnd) { + if (configurableEnd === void 0) { configurableEnd = useNonAdjustedPositions; } + return !!getEndPositionOfMultilineTrailingComment(sourceFile, oldNode, configurableEnd); + }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { var next = ts.findNextToken(node, node.parent, sourceFile); return next && next.kind === 27 /* CommaToken */ ? next : undefined; @@ -138825,47 +139104,22 @@ var ts; // a, b, c // create change for adding 'e' after 'a' as // - find start of next element after a (it is b) - // - use this start as start and end position in final change - // - build text of change by formatting the text of node + separator + whitespace trivia of b + // - use next element start as start and end position in final change + // - build text of change by formatting the text of node + whitespace trivia of b // in multiline case it will work as // a, // b, // c, // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') - // a,* - // ***insertedtext# + // a, + // insertedtext# // ###b, // c, - // find line and character of the next element - var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); - // find line and character of the token that precedes next element (usually it is separator) - var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); - var prefix = void 0; - var startPos = void 0; - if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { - // next element is located on the same line with separator: - // a,$$$$b - // ^ ^ - // | |-next element - // |-separator - // where $$$ is some leading trivia - // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces - // a, x,$$$$b - // ^ ^ ^ - // | | |-next element - // | |-new inserted node padded with spaces - // |-separator - startPos = nextToken.end; - prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); - } - else { - // next element is located on different line that separator - // let insert position be the beginning of the line that contains next element - startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); - } + var nextNode = containingList[index + 1]; + var startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart()); // write separator and leading trivia of the next element as suffix - var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, startPos); + this.insertNodesAt(sourceFile, startPos, [newNode], { suffix: suffix }); } } else { @@ -139396,7 +139650,9 @@ var ts; case 261 /* ImportEqualsDeclaration */: var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); // For first import, leave header comment in place, otherwise only delete JSDoc comments - deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + deleteNode(changes, sourceFile, node, { + leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine, + }); break; case 199 /* BindingElement */: var pattern = node.parent; @@ -139822,7 +140078,7 @@ var ts; ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code, - ts.Diagnostics.This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, ts.Diagnostics.Type_0_is_not_an_array_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators.code, @@ -140713,7 +140969,7 @@ var ts; functionToConvert = tokenAtPosition.parent.initializer; } else { - functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.canBeConvertedToAsync); } if (!functionToConvert) { return; @@ -140722,6 +140978,9 @@ var ts; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); + if (!ts.returnsPromise(functionToConvertRenamed, checker)) { + return; + } var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray; var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { @@ -142339,6 +142598,10 @@ var ts; if (!importClause || !ts.isStringLiteralLike(declaration.moduleSpecifier)) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; + // A type-only import may not have both a default and named imports, so the only way a name can + // be added to an existing type-only import is adding a named import to existing named bindings. + if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) + return undefined; return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 265 /* NamedImports */) ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.text, canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; @@ -142872,7 +143135,8 @@ var ts; ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, - ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code ]; var errorCodeFixIdMap = (_a = {}, _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code] = [ @@ -142881,6 +143145,9 @@ var ts; _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code] = [ ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers ], + _a[ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, + ], _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code] = [ ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers ], @@ -142919,6 +143186,7 @@ var ts; switch (errorCode) { case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: @@ -142928,16 +143196,23 @@ var ts; } } function doAddOverrideModifierChange(changeTracker, sourceFile, pos) { - var classElement = findContainerClassElement(sourceFile, pos); - changeTracker.insertModifierBefore(sourceFile, 156 /* OverrideKeyword */, classElement); + var classElement = findContainerClassElementLike(sourceFile, pos); + var modifiers = classElement.modifiers || ts.emptyArray; + var staticModifier = ts.find(modifiers, ts.isStaticModifier); + var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var modifierPos = staticModifier ? staticModifier.end : + accessibilityModifier ? accessibilityModifier.end : + classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + var options = accessibilityModifier || staticModifier ? { prefix: " " } : { suffix: " " }; + changeTracker.insertModifierAt(sourceFile, modifierPos, 156 /* OverrideKeyword */, options); } function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { - var classElement = findContainerClassElement(sourceFile, pos); + var classElement = findContainerClassElementLike(sourceFile, pos); var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 156 /* OverrideKeyword */; }); ts.Debug.assertIsDefined(overrideModifier); changeTracker.deleteModifier(sourceFile, overrideModifier); } - function isClassElementHasJSDoc(node) { + function isClassElementLikeHasJSDoc(node) { switch (node.kind) { case 167 /* Constructor */: case 164 /* PropertyDeclaration */: @@ -142945,18 +143220,20 @@ var ts; case 168 /* GetAccessor */: case 169 /* SetAccessor */: return true; + case 161 /* Parameter */: + return ts.isParameterPropertyDeclaration(node, node.parent); default: return false; } } - function findContainerClassElement(sourceFile, pos) { + function findContainerClassElementLike(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); var classElement = ts.findAncestor(token, function (node) { if (ts.isClassLike(node)) return "quit"; - return isClassElementHasJSDoc(node); + return isClassElementLikeHasJSDoc(node); }); - ts.Debug.assert(classElement && isClassElementHasJSDoc(classElement)); + ts.Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); return classElement; } })(codefix = ts.codefix || (ts.codefix = {})); @@ -143673,11 +143950,11 @@ var ts; var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, 1 /* NoTruncation */); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */) : undefined; } return typeNode || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } @@ -144807,7 +145084,7 @@ var ts; (function (codefix) { var fixId = "fixMissingCallParentheses"; var errorCodes = [ - ts.Diagnostics.This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -147538,7 +147815,7 @@ var ts; 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 flags = ts.getSyntacticModifierFlags(exportNode); + var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ExportDefault */ : 0 /* None */); var wasDefault = !!(flags & 512 /* Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { @@ -147566,6 +147843,11 @@ var ts; ts.Debug.assert(!wasDefault, "Can't have a default flag here"); return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } + case 267 /* ExportAssignment */: { + var node = exportNode; + var exp = node.expression; + return node.isExportEquals ? undefined : { exportNode: node, exportName: exp, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol }; + } default: return undefined; } @@ -147577,7 +147859,14 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + 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]))); + } + else { + changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + } } else { var exportKeyword = ts.Debug.checkDefined(ts.findModifier(exportNode, 92 /* ExportKeyword */), "Should find an export keyword in modifier list"); @@ -147604,7 +147893,7 @@ var ts; changes.insertNodeAfter(exportingSourceFile, exportNode, ts.factory.createExportDefault(ts.factory.createIdentifier(exportName.text))); break; default: - ts.Debug.assertNever(exportNode, "Unexpected exportNode kind " + exportNode.kind); + ts.Debug.fail("Unexpected exportNode kind " + exportNode.kind); } } } @@ -148533,7 +148822,7 @@ var ts; return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } var cursorRequest = length === 0 && invoked; - var startToken = ts.getTokenAtPosition(sourceFile, span.start); + var startToken = ts.findFirstNonJsxWhitespaceToken(sourceFile, span.start); var endToken = ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)); /* If the refactoring command is invoked through a keyboard action it's safe to assume that the user is actively looking for refactoring actions at the span location. As they may not know the exact range that will trigger a refactoring, we expand the @@ -152342,8 +152631,8 @@ var ts; var list = createNode(338 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; addSyntheticNodes(list._children, pos, node.pos, parent); list._children.push(node); pos = node.end; @@ -152785,7 +153074,7 @@ var ts; break; case 161 /* Parameter */: // Only consider parameter properties - if (!ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { break; } // falls through @@ -153366,7 +153655,7 @@ var ts; // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); } function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); @@ -153411,8 +153700,13 @@ 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" - ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind."); - return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + 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); + } } // We didn't already have the file. Fall through and acquire it from the registry. } @@ -153441,7 +153735,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); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); }); program = undefined; // TODO: GH#18217 } @@ -153541,7 +153835,7 @@ var ts; function shouldGetType(sourceFile, node, position) { switch (node.kind) { case 78 /* Identifier */: - return !ts.isLabelName(node) && !ts.isTagName(node); + return !ts.isLabelName(node) && !ts.isTagName(node) && !ts.isConstTypeReference(node.parent); case 202 /* PropertyAccessExpression */: case 158 /* QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` @@ -153707,15 +154001,7 @@ var ts; function getNavigationTree(fileName) { return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); } - function isTsOrTsxFile(fileName) { - var kind = ts.getScriptKind(fileName, host); - return kind === 3 /* TS */ || kind === 4 /* TSX */; - } function getSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return []; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "2020" /* TwentyTwenty */) { @@ -153726,10 +154012,6 @@ var ts; } } function getEncodedSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return { spans: [], endOfLineState: 0 /* None */ }; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "original" /* Original */) { @@ -153820,13 +154102,13 @@ var ts; var formatContext = ts.formatting.getFormatContext(formatOptions, host); return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions, preferences) { + function organizeImports(args, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - ts.Debug.assert(scope.type === "file"); - var sourceFile = getValidSourceFile(scope.fileName); + ts.Debug.assert(args.type === "file"); + var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } @@ -158692,7 +158974,7 @@ var ts; } /*@internal*/ AutoImportProviderProject.getRootFileNames = function (dependencySelection, hostProject, moduleResolutionHost, compilerOptions) { - var _a, _b, _c, _d; + var _a, _b, _c; if (!dependencySelection) { return ts.emptyArray; } @@ -158707,18 +158989,22 @@ var ts; } if (dependencyNames) { var resolutions = ts.map(ts.arrayFrom(dependencyNames.keys()), function (name) { return ts.resolveTypeReferenceDirective(name, rootFileName, compilerOptions, moduleResolutionHost); }); - for (var _e = 0, resolutions_1 = resolutions; _e < resolutions_1.length; _e++) { - var resolution = resolutions_1[_e]; + var program = hostProject.getCurrentProgram(); + var symlinkCache = hostProject.getSymlinkCache(); + for (var _d = 0, resolutions_1 = resolutions; _d < resolutions_1.length; _d++) { + var resolution = resolutions_1[_d]; if (!((_c = resolution.resolvedTypeReferenceDirective) === null || _c === void 0 ? void 0 : _c.resolvedFileName)) continue; - var resolvedFileName = resolution.resolvedTypeReferenceDirective.resolvedFileName; - var fileName = ((_d = moduleResolutionHost.realpath) === null || _d === void 0 ? void 0 : _d.call(moduleResolutionHost, resolvedFileName)) || resolvedFileName; - if (!hostProject.getCurrentProgram().getSourceFile(fileName) && !hostProject.getCurrentProgram().getSourceFile(resolvedFileName)) { - rootNames = ts.append(rootNames, fileName); + var _e = resolution.resolvedTypeReferenceDirective, resolvedFileName = _e.resolvedFileName, originalPath = _e.originalPath; + if (!program.getSourceFile(resolvedFileName) && (!originalPath || !program.getSourceFile(originalPath))) { + rootNames = ts.append(rootNames, resolvedFileName); // Avoid creating a large project that would significantly slow down time to editor interactivity if (dependencySelection === 2 /* Auto */ && rootNames.length > this.maxDependencies) { return ts.emptyArray; } + if (originalPath) { + symlinkCache.setSymlinkedDirectoryFromSymlinkedFile(originalPath, resolvedFileName); + } } } } @@ -163810,7 +164096,7 @@ var ts; Session.prototype.mapDefinitionInfoLocations = function (definitions, project) { return definitions.map(function (info) { var newDocumentSpan = getMappedDocumentSpan(info, project); - return !newDocumentSpan ? info : __assign(__assign({}, newDocumentSpan), { containerKind: info.containerKind, containerName: info.containerName, kind: info.kind, name: info.name }); + return !newDocumentSpan ? info : __assign(__assign(__assign({}, newDocumentSpan), { containerKind: info.containerKind, containerName: info.containerName, kind: info.kind, name: info.name }), info.unverified && { unverified: info.unverified }); }); }; Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) { @@ -163868,7 +164154,7 @@ var ts; }; Session.prototype.mapDefinitionInfo = function (definitions, project) { var _this = this; - return definitions.map(function (def) { return _this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project); }); + return definitions.map(function (def) { return (__assign(__assign({}, _this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project)), def.unverified && { unverified: def.unverified })); }); }; /* * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in @@ -164319,10 +164605,10 @@ var ts; var prefix = args.prefix || ""; var entries = ts.stableSort(ts.mapDefined(completions.entries, function (entry) { if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, sourceDisplay = entry.sourceDisplay, isSnippet = entry.isSnippet, isRecommended = entry.isRecommended, isPackageJsonImport = entry.isPackageJsonImport, data = entry.data; + var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, sourceDisplay = entry.sourceDisplay, isSnippet = entry.isSnippet, isRecommended = entry.isRecommended, isPackageJsonImport = entry.isPackageJsonImport, isImportStatementCompletion = entry.isImportStatementCompletion, data = entry.data; var convertedSpan = replacementSpan ? toProtocolTextSpan(replacementSpan, scriptInfo) : undefined; // Use `hasAction || undefined` to avoid serializing `false`. - return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, isSnippet: isSnippet, hasAction: hasAction || undefined, source: source, sourceDisplay: sourceDisplay, isRecommended: isRecommended, isPackageJsonImport: isPackageJsonImport, data: data }; + return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, isSnippet: isSnippet, hasAction: hasAction || undefined, source: source, sourceDisplay: sourceDisplay, isRecommended: isRecommended, isPackageJsonImport: isPackageJsonImport, isImportStatementCompletion: isImportStatementCompletion, data: data }; } }), function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); if (kind === "completions" /* Completions */) { @@ -164616,11 +164902,14 @@ var ts; return result; } }; - Session.prototype.organizeImports = function (_a, simplifiedResult) { - var scope = _a.scope; - ts.Debug.assert(scope.type === "file"); - var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; - var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file)); + Session.prototype.organizeImports = function (args, simplifiedResult) { + ts.Debug.assert(args.scope.type === "file"); + var _a = this.getFileAndProject(args.scope.args), file = _a.file, project = _a.project; + var changes = project.getLanguageService().organizeImports({ + fileName: file, + skipDestructiveCodeActions: args.skipDestructiveCodeActions, + type: "file", + }, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { return this.mapTextChangesToCodeEdits(changes); } diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 0b2d291eeddb5..b86a3a29970a4 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -540,7 +540,7 @@ declare namespace ts { Override = 16384, HasComputedFlags = 536870912, AccessibilityModifier = 28, - ParameterPropertyModifier = 92, + ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, TypeScriptModifier = 18654, ExportDefault = 513, @@ -563,7 +563,7 @@ declare namespace ts { } export interface JSDocContainer { } - export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; + export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | EmptyStatement | DebuggerStatement | Block | VariableStatement | ExpressionStatement | IfStatement | DoStatement | WhileStatement | ForStatement | ForInStatement | ForOfStatement | BreakStatement | ContinueStatement | ReturnStatement | WithStatement | SwitchStatement | LabeledStatement | ThrowStatement | TryStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; 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; @@ -1380,7 +1380,7 @@ declare namespace ts { readonly containsOnlyTriviaWhiteSpaces: boolean; } export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; - export interface Statement extends Node { + export interface Statement extends Node, JSDocContainer { _statementBrand: any; } export interface NotEmittedStatement extends Statement { @@ -1408,11 +1408,11 @@ declare namespace ts { readonly kind: SyntaxKind.Block; readonly statements: NodeArray; } - export interface VariableStatement extends Statement, JSDocContainer { + export interface VariableStatement extends Statement { readonly kind: SyntaxKind.VariableStatement; readonly declarationList: VariableDeclarationList; } - export interface ExpressionStatement extends Statement, JSDocContainer { + export interface ExpressionStatement extends Statement { readonly kind: SyntaxKind.ExpressionStatement; readonly expression: Expression; } @@ -1493,7 +1493,7 @@ declare namespace ts { readonly statements: NodeArray; } export type CaseOrDefaultClause = CaseClause | DefaultClause; - export interface LabeledStatement extends Statement, JSDocContainer { + export interface LabeledStatement extends Statement { readonly kind: SyntaxKind.LabeledStatement; readonly label: Identifier; readonly statement: Statement; @@ -1613,7 +1613,7 @@ declare namespace ts { readonly parent: ImportEqualsDeclaration; readonly expression: Expression; } - export interface ImportDeclaration extends Statement, JSDocContainer { + export interface ImportDeclaration extends Statement { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; readonly importClause?: ImportClause; @@ -2291,8 +2291,7 @@ declare namespace ts { IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, - InInitialEntityName = 16777216, - InReverseMappedType = 33554432 + InInitialEntityName = 16777216 } export enum TypeFormatFlags { None = 0, @@ -2560,15 +2559,15 @@ declare namespace ts { ObjectLiteral = 128, EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, - ContainsSpread = 1024, - ReverseMapped = 2048, - JsxAttributes = 4096, - MarkerType = 8192, - JSLiteral = 16384, - FreshLiteral = 32768, - ArrayLiteral = 65536, - ObjectRestType = 131072, + ReverseMapped = 1024, + JsxAttributes = 2048, + MarkerType = 4096, + JSLiteral = 8192, + FreshLiteral = 16384, + ArrayLiteral = 32768, ClassOrInterface = 3, + ContainsSpread = 4194304, + ObjectRestType = 8388608, } export interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2682,6 +2681,7 @@ declare namespace ts { type: Type; } export interface SubstitutionType extends InstantiableType { + objectFlags: ObjectFlags; baseType: Type; substitute: Type; } @@ -2706,16 +2706,17 @@ declare namespace ts { export enum InferencePriority { NakedTypeVariable = 1, SpeculativeTuple = 2, - HomomorphicMappedType = 4, - PartialHomomorphicMappedType = 8, - MappedTypeConstraint = 16, - ContravariantConditional = 32, - ReturnType = 64, - LiteralKeyof = 128, - NoConstraints = 256, - AlwaysStrict = 512, - MaxValue = 1024, - PriorityImpliesCombination = 208, + SubstituteSource = 4, + HomomorphicMappedType = 8, + PartialHomomorphicMappedType = 16, + MappedTypeConstraint = 32, + ContravariantConditional = 64, + ReturnType = 128, + LiteralKeyof = 256, + NoConstraints = 512, + AlwaysStrict = 1024, + MaxValue = 2048, + PriorityImpliesCombination = 416, Circularity = -1 } /** @deprecated Use FileExtensionInfo instead. */ @@ -4708,13 +4709,13 @@ declare namespace ts { export {}; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; + export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -4723,30 +4724,46 @@ declare namespace ts { * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResolutionCache, PackageJsonInfoCache { + } /** - * Cached module resolutions per containing directory. + * Cached resolutions per containing directory. * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ - interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + export interface PerDirectoryResolutionCache { + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + clear(): void; + /** + * Updates with the current compilerOptions the cache will operate with. + * This updates the redirects map as well if needed so module resolutions are cached if they can across the projects + */ + update(options: CompilerOptions): void; + } + export interface ModuleResolutionCache extends PerDirectoryResolutionCache, NonRelativeModuleNameResolutionCache, PackageJsonInfoCache { + getPackageJsonInfoCache(): PackageJsonInfoCache; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ - interface NonRelativeModuleNameResolutionCache { + export interface NonRelativeModuleNameResolutionCache extends PackageJsonInfoCache { getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } - interface PerModuleNameCache { + export interface PackageJsonInfoCache { + clear(): void; + } + export interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } - function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; - function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; + export function createTypeReferenceDirectiveResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions, packageJsonInfoCache?: PackageJsonInfoCache): TypeReferenceDirectiveResolutionCache; + export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; + export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export {}; } declare namespace ts { /** @@ -5202,9 +5219,9 @@ declare namespace ts { interface SolutionBuilderWithWatchHost extends SolutionBuilderHostBase, WatchHost { } interface SolutionBuilder { - build(project?: string, cancellationToken?: CancellationToken): ExitStatus; + build(project?: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; clean(project?: string): ExitStatus; - buildReferences(project: string, cancellationToken?: CancellationToken): ExitStatus; + buildReferences(project: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; cleanReferences(project?: string): ExitStatus; getNextInvalidatedProject(cancellationToken?: CancellationToken): InvalidatedProject | undefined; } @@ -5650,7 +5667,7 @@ declare namespace ts { applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; + organizeImports(args: OrganizeImportsArgs, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; @@ -5667,7 +5684,9 @@ declare namespace ts { type: "file"; fileName: string; } - type OrganizeImportsScope = CombinedCodeFixScope; + interface OrganizeImportsArgs extends CombinedCodeFixScope { + skipDestructiveCodeActions?: boolean; + } type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; interface GetCompletionsAtPositionOptions extends UserPreferences { /** @@ -6196,6 +6215,7 @@ declare namespace ts { isRecommended?: true; isFromUncheckedFile?: true; isPackageJsonImport?: true; + isImportStatementCompletion?: true; /** * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, * that allows TS Server to look up the symbol represented by the completion item, disambiguating @@ -6517,8 +6537,23 @@ declare namespace ts { * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file */ + /**@deprecated pass scriptKind for correctness */ releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @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 + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind): void; + /** + * @deprecated pass scriptKind for correctness */ releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind): void; reportStats(): string; } type DocumentRegistryBucketKey = string & { diff --git a/lib/typescript.js b/lib/typescript.js index 9c998682479cc..6f5f1ca180fe6 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -290,7 +290,7 @@ var ts; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-beta"; + ts.version = "4.3.1-rc"; /* @internal */ var Comparison; (function (Comparison) { @@ -2856,11 +2856,11 @@ var ts; this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : - this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" : + this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; - var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0; + var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); } }, @@ -3881,7 +3881,7 @@ var ts; }; } var reverseMappedProperties = {}; - if (objectFlags & 2048 /* ReverseMapped */) { + if (objectFlags & 1024 /* ReverseMapped */) { var reverseMappedType = type; reverseMappedProperties = { reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id, @@ -4422,7 +4422,7 @@ var ts; 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. - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 18654] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; @@ -4623,7 +4623,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; - NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -4976,6 +4975,9 @@ var ts; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags + // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check + // for a certain TypeFlags value to determine their meaning. var ObjectFlags; (function (ObjectFlags) { ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; @@ -4988,50 +4990,59 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; - ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; - ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; - ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; - ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; - ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; - ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 1024] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 2048] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 4096] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 8192] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 16384] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ArrayLiteral"] = 32768] = "ArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 262144] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; + ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 1048576] = "CouldContainTypeVariablesComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; + ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 2097152] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags"; + // Object flags that uniquely identify the kind of ObjectType /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; + ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask"; + // Flags that require TypeFlags.Object + ObjectFlags[ObjectFlags["ContainsSpread"] = 4194304] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 8388608] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone"; + // Flags that require TypeFlags.Object and ObjectFlags.Reference /* @internal */ - ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated"; /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists"; + // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; + ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; + ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; - // Object flags that uniquely identify the kind of ObjectType + ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + // Flags that require TypeFlags.Union + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 67108864] = "ContainsIntersections"; + // Flags that require TypeFlags.Intersection /* @internal */ - ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask"; + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 67108864] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 134217728] = "IsNeverIntersection"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -5105,16 +5116,17 @@ var ts; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple"; - InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType"; - InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType"; - InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint"; - InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional"; - InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType"; - InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof"; - InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict"; - InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue"; - InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination"; + InferencePriority[InferencePriority["SubstituteSource"] = 4] = "SubstituteSource"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 8] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 16] = "PartialHomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 32] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ContravariantConditional"] = 64] = "ContravariantConditional"; + InferencePriority[InferencePriority["ReturnType"] = 128] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 256] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 512] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 1024] = "AlwaysStrict"; + InferencePriority[InferencePriority["MaxValue"] = 2048] = "MaxValue"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 416] = "PriorityImpliesCombination"; InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); /* @internal */ @@ -8051,7 +8063,7 @@ var ts; A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), - An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), @@ -8077,6 +8089,7 @@ var ts; A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), @@ -8163,7 +8176,7 @@ var ts; Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."), - The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."), + The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8205,6 +8218,7 @@ var ts; The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), + Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."), 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), @@ -8453,14 +8467,13 @@ var ts; The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), - Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), @@ -8483,17 +8496,17 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), @@ -8578,7 +8591,7 @@ var ts; Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), @@ -8586,14 +8599,14 @@ var ts; _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), - A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), @@ -8655,7 +8668,7 @@ var ts; The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), - This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_2774", "This condition will always return true since this function appears to always be defined. Did you mean to call it instead?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), @@ -8682,7 +8695,7 @@ var ts; The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), - This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined_2801", "This condition will always return true since this '{0}' appears to always be defined."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), @@ -8691,6 +8704,9 @@ var ts; This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), + Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), + Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), 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}'."), @@ -8788,7 +8804,7 @@ var ts; This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), - This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_becaus_4115", "This parameter property must be rewritten as a property declaration with an 'override' modifier because it overrides a member in base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), 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."), @@ -8824,7 +8840,7 @@ var ts; Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), - Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), @@ -8837,12 +8853,14 @@ var ts; Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), - A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -9066,7 +9084,11 @@ var ts; Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), - Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -9114,6 +9136,7 @@ var ts; _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), 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."), @@ -9155,7 +9178,7 @@ var ts; Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -9195,7 +9218,7 @@ var ts; JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), @@ -9880,11 +9903,11 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; /* @internal */ - function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { - if (stopAtComments === void 0) { stopAtComments = false; } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (ts.positionIsSynthesized(pos)) { return pos; } + var canConsumeStar = false; // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -9899,6 +9922,7 @@ var ts; if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case 9 /* tab */: case 11 /* verticalTab */: @@ -9918,6 +9942,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { @@ -9929,6 +9954,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } break; @@ -9938,12 +9964,21 @@ var ts; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; case 35 /* hash */: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42 /* asterisk */: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -11994,7 +12029,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; + return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -12310,7 +12345,7 @@ var ts; if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } ts.getNameOfDeclaration = getNameOfDeclaration; /*@internal*/ @@ -12865,7 +12900,7 @@ var ts; ts.isModifierKind = isModifierKind; /* @internal */ function isParameterPropertyModifier(kind) { - return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + return !!(ts.modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */); } ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ @@ -13825,7 +13860,9 @@ var ts; } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { @@ -14078,7 +14115,9 @@ var ts; if (node.kind === 338 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ false, isInJSDoc(node)); } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -15513,6 +15552,10 @@ var ts; return node.kind === 177 /* TypeQuery */; } ts.isPartOfTypeQuery = isPartOfTypeQuery; + function isNamespaceReexportDeclaration(node) { + return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 273 /* ExternalModuleReference */; } @@ -16125,6 +16168,7 @@ var ts; parent.kind === 267 /* ExportAssignment */ || parent.kind === 164 /* PropertyDeclaration */ || parent.kind === 234 /* ExpressionStatement */ && node.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 243 /* ReturnStatement */ || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) { return parent; @@ -19325,6 +19369,10 @@ var ts; return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; + function getUseDefineForClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === 99 /* ESNext */ : compilerOptions.useDefineForClassFields; + } + ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return oldOptions !== newOptions && ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); @@ -19396,19 +19444,33 @@ var ts; } (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); } - } + }, + setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { + this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); + var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var cache = createSymlinkCache(cwd, getCanonicalFileName); - var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { - return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + var symlinks = ts.flatMap(files, function (sf) { + var pairs = sf.resolvedModules && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedModules.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) ? [res.resolvedFileName, res.originalPath] : undefined; + })); + return ts.concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] : undefined; }))); - })); + }); for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); @@ -20405,7 +20467,11 @@ var ts; var ts; (function (ts) { function createParenthesizerRules(factory) { + var binaryLeftOperandParenthesizerCache; + var binaryRightOperandParenthesizerCache; return { + getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName, @@ -20426,6 +20492,24 @@ var ts; parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType, parenthesizeTypeArguments: parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); }; + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); }; + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } /** * Determines whether the operand to a BinaryExpression needs to be parenthesized. * @@ -20754,6 +20838,8 @@ var ts; } ts.createParenthesizerRules = createParenthesizerRules; ts.nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; }, + getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; }, parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; }, parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; }, parenthesizeExpressionOfComputedPropertyName: ts.identity, @@ -21695,6 +21781,7 @@ var ts; case 155 /* BigIntKeyword */: case 141 /* NeverKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 147 /* StringKeyword */: case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: @@ -21777,15 +21864,15 @@ var ts; if (flags & 32 /* Static */) { result.push(createModifier(123 /* StaticKeyword */)); } + if (flags & 16384 /* Override */) { + result.push(createModifier(156 /* OverrideKeyword */)); + } if (flags & 64 /* Readonly */) { result.push(createModifier(142 /* ReadonlyKeyword */)); } if (flags & 256 /* Async */) { result.push(createModifier(129 /* AsyncKeyword */)); } - if (flags & 16384 /* Override */) { - result.push(createModifier(156 /* OverrideKeyword */)); - } return result; } // @@ -21857,7 +21944,7 @@ var ts; propagateChildFlags(node.questionToken); if (questionToken) node.transformFlags |= 1 /* ContainsTypeScript */; - if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */) + if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */) node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) node.transformFlags |= 512 /* ContainsES2015 */; @@ -22524,7 +22611,7 @@ var ts; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { var node = createBaseBindingLikeDeclaration(199 /* BindingElement */, /*decorators*/ undefined, - /*modifiers*/ undefined, name, initializer); + /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= @@ -29360,6 +29447,7 @@ var ts; case 324 /* JSDocPrivateTag */: case 325 /* JSDocProtectedTag */: case 326 /* JSDocReadonlyTag */: + case 321 /* JSDocDeprecatedTag */: return visitNode(cbNode, node.tagName) || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); case 340 /* PartiallyEmittedExpression */: @@ -31450,19 +31538,21 @@ var ts; function parseParameterWorker(inOuterAwaitContext) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); + // 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(); if (token() === 107 /* ThisKeyword */) { - var node_1 = factory.createParameterDeclaration( - /*decorators*/ undefined, + var node_1 = factory.createParameterDeclaration(decorators, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); + if (decorators) { + parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } return withJSDoc(finishNode(node_1, pos), hasJSDoc); } - // 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 savedTopLevel = topLevel; topLevel = false; var modifiers = parseModifiers(); @@ -33748,12 +33838,13 @@ var ts; // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var openBracePosition = scanner.getTokenPos(); if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { var multiLine = scanner.hasPrecedingLineBreak(); var statements = parseList(1 /* BlockStatements */, parseStatement); parseExpectedMatchingBrackets(18 /* OpenBraceToken */, 19 /* CloseBraceToken */, openBracePosition); - var result = finishNode(factory.createBlock(statements, multiLine), pos); + var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); if (token() === 62 /* EqualsToken */) { parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); nextToken(); @@ -33762,7 +33853,7 @@ var ts; } else { var statements = createMissingList(); - return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -33789,11 +33880,13 @@ var ts; } function parseEmptyStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(26 /* SemicolonToken */); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(98 /* IfKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); @@ -33801,10 +33894,11 @@ var ts; parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var thenStatement = parseStatement(); var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(89 /* DoKeyword */); var statement = parseStatement(); parseExpected(114 /* WhileKeyword */); @@ -33817,20 +33911,22 @@ var ts; // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. parseOptional(26 /* SemicolonToken */); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(114 /* WhileKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(96 /* ForKeyword */); var awaitToken = parseOptionalToken(130 /* AwaitKeyword */); parseExpected(20 /* OpenParenToken */); @@ -33866,34 +33962,37 @@ var ts; parseExpected(21 /* CloseParenToken */); node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(kind === 242 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); var node = kind === 242 /* BreakStatement */ ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(104 /* ReturnKeyword */); var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(115 /* WithKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { var pos = getNodePos(); @@ -33922,17 +34021,19 @@ var ts; } function parseSwitchStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(106 /* SwitchKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { // ThrowStatement[Yield] : // throw [no LineTerminator here]Expression[In, ?Yield]; var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(108 /* ThrowKeyword */); // Because of automatic semicolon insertion, we need to report error if this // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' @@ -33945,11 +34046,12 @@ var ts; expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } // TODO: Review for error recovery function parseTryStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(110 /* TryKeyword */); var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -33960,7 +34062,7 @@ var ts; parseExpected(95 /* FinallyKeyword */); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { var pos = getNodePos(); @@ -33979,9 +34081,10 @@ var ts; } function parseDebuggerStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(86 /* DebuggerKeyword */); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement() { // Avoiding having to do the lookahead for a labeled statement by just trying to parse @@ -35368,7 +35471,6 @@ var ts; state = 2 /* SavingComments */; var commentEnd = scanner.getStartPos(); var linkStart = scanner.getTextPos() - 1; - // TODO: redo here var link = parseJSDocLink(linkStart); if (link) { if (!linkEnd) { @@ -35570,8 +35672,9 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */ || !previousWhitespace && state === 2 /* SavingComments */) { - // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace + if (state === 3 /* SavingBackticks */ + || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace comments.push(scanner.getTokenText()); break; } @@ -35648,6 +35751,10 @@ var ts; return comments.join(""); } } + function isNextJSDocTokenWhitespace() { + var next = nextTokenJSDoc(); + return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */; + } function parseJSDocLink(start) { if (!tryParse(parseJSDocLinkPrefix)) { return undefined; @@ -37151,8 +37258,8 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - /* @internal */ - ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsWithoutBuild = [ + // CommandLine only options { name: "all", type: "boolean", @@ -37938,7 +38045,9 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins }, - ]); + ]; + /* @internal */ + ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsWithoutBuild); /* @internal */ ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); /* @internal */ @@ -37953,8 +38062,7 @@ var ts; ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) { return ts.hasProperty(option, "transpileOptionValue"); }); - /* @internal */ - ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsOnlyBuild = [ { name: "verbose", shortName: "v", @@ -37982,7 +38090,9 @@ var ts; description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean" } - ]); + ]; + /* @internal */ + ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsOnlyBuild); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -38036,6 +38146,10 @@ var ts; return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations)); } ts.getOptionsNameMap = getOptionsNameMap; + var compilerOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; /* @internal */ ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, @@ -38097,6 +38211,10 @@ var ts; return option.name; } function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { + var _a; + if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -38251,6 +38369,7 @@ var ts; } /*@internal*/ ts.compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -38283,7 +38402,12 @@ var ts; function getBuildOptionsNameMap() { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts)); } + var buildOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap: getOptionsNameMap + }; var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: ts.buildOpts, unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, @@ -40034,13 +40158,24 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) { var traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined; + var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -40063,6 +40198,8 @@ var ts; trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); } } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -40073,17 +40210,31 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary: primary, + resolvedFileName: resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId: packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, result); + if (traceEnabled) + traceResult(result); + return result; + function traceResult(result) { + var _a; + if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { // Check primary library paths if (typeRoots && typeRoots.length) { @@ -40113,20 +40264,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = void 0; + var result_4; if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); - result = searchResult && searchResult.value; + result_4 = searchResult && searchResult.value; } else { var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; - result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); } - var resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - return resolvedFile; + return resolvedTypeScriptOnly(result_4); } else { if (traceEnabled) { @@ -40181,22 +40328,21 @@ var ts; return result; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName); - } - ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ function createCacheWithRedirects(options) { var ownMap = new ts.Map(); var redirectsMap = new ts.Map(); return { - ownMap: ownMap, + getOwnMap: getOwnMap, redirectsMap: redirectsMap, getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, clear: clear, setOwnOptions: setOwnOptions, setOwnMap: setOwnMap }; + function getOwnMap() { + return ownMap; + } function setOwnOptions(newOptions) { options = newOptions; } @@ -40222,26 +40368,88 @@ var ts; } } ts.createCacheWithRedirects = createCacheWithRedirects; - /*@internal*/ - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap }; + function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + var cache; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear }; + function getPackageJsonInfo(packageJsonPath) { + return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + if (!options.configFile) + return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + // The own map will be for projectCompilerOptions + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + // Set correct own map + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + var ref = { + sourceFile: options.configFile, + commandLine: { options: options } + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options); + } + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) { + return { + getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, + clear: clear, + update: update, + }; + function clear() { + directoryToModuleNameMap.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap); + } function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); }); } + } + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + var preDirectoryResolutionCache = 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; } }); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + packageJsonInfoCache.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); + } function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } - function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { - var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - var result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; - } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); return { get: get, set: set }; @@ -40308,7 +40516,17 @@ var ts; } } } - ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + ts.createModuleResolutionCache = createModuleResolutionCache; + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache.clear(); + } + } + ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache) { var containingDirectory = ts.getDirectoryPath(containingFile); var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -40586,7 +40804,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; 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, state.resultFromCache); function tryResolve(extensions) { @@ -40646,7 +40864,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -40679,8 +40897,9 @@ var ts; * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo" * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo" */ + /* @internal */ function parseNodeModuleFromPath(resolved) { - var path = ts.normalizePath(resolved.path); + var path = ts.normalizePath(resolved); var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; @@ -40692,6 +40911,7 @@ var ts; } return path.slice(0, indexAfterPackageName); } + ts.parseNodeModuleFromPath = parseNodeModuleFromPath; function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; @@ -40775,21 +40995,43 @@ var ts; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c; var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) + trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) + trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + var directoryExists = ts.directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = ts.readJson(packageJsonPath, host); if (traceEnabled) { trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists); // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results state.failedLookupLocations.push(packageJsonPath); } @@ -41038,7 +41280,7 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath @@ -41079,13 +41321,13 @@ var ts; * This is the minumum code needed to expose that functionality; the rest is in the host. */ /* @internal */ - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { 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 state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache); } @@ -41731,6 +41973,7 @@ var ts; } if (node.kind === 298 /* SourceFile */) { node.flags |= emitFlags; + node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -43048,9 +43291,9 @@ var ts; var saveCurrentFlow = currentFlow; for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { var typeAlias = delayedTypeAliases_1[_i]; - var host = ts.getJSDocHost(typeAlias); - container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); })) || file; - blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file; + var host = typeAlias.parent.parent; + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -43636,8 +43879,8 @@ var ts; } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + // Incorrect export assignment in some sort of block construct + bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node)); } else { var flags = ts.exportAssignmentIsAlias(node) @@ -44815,6 +45058,7 @@ var ts; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -44823,7 +45067,7 @@ var ts; var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384 /* FreshLiteral */; var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); @@ -45010,6 +45254,7 @@ var ts; return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, + getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, argumentCount) { return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */); @@ -45181,14 +45426,14 @@ var ts; var autoType = createIntrinsicType(1 /* Any */, "any"); var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); - var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */); + var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 131072 /* ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -45214,7 +45459,7 @@ var ts; var voidType = createIntrinsicType(16384 /* Void */, "void"); var neverType = createIntrinsicType(131072 /* Never */, "never"); var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -45226,7 +45471,7 @@ var ts; var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -45235,7 +45480,7 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */; + anyFunctionType.objectFlags |= 524288 /* NonInferrableType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -45897,7 +46142,7 @@ var ts; } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property - return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -45925,7 +46170,7 @@ var ts; return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); @@ -46060,7 +46305,7 @@ var ts; case 164 /* PropertyDeclaration */: // static properties in classes introduce temporary variables if (ts.hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + return target < 99 /* ESNext */ || !useDefineForClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -46445,7 +46690,7 @@ var ts; } // Perform extra checks only if error reporting was requested if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* 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. @@ -46776,8 +47021,7 @@ var ts; } } function getDeclarationOfAliasSymbol(symbol) { - var _a; - return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(isAliasSymbolDeclaration); + return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration); } /** * An alias symbol is created by one of the following declarations: @@ -46792,6 +47036,7 @@ var ts; * module.exports = * {} * {name: } + * const { x } = require ... */ function isAliasSymbolDeclaration(node) { return node.kind === 261 /* ImportEqualsDeclaration */ @@ -47022,7 +47267,7 @@ var ts; return undefined; } var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -48098,7 +48343,7 @@ var ts; var _loop_8 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } } @@ -48113,7 +48358,7 @@ var ts; // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred // to one another anyway) - if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) { + if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } break; @@ -48145,7 +48390,7 @@ var ts; if (typeof state_2 === "object") return state_2.value; } - return callback(globals); + return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace @@ -48165,11 +48410,11 @@ var ts; /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) */ - function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols, ignoreQualification); + var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables.pop(); return result; } @@ -48187,7 +48432,7 @@ var ts; !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols, ignoreQualification) { + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { // If symbol is directly available by its name in the symbol table if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; @@ -48200,6 +48445,8 @@ var ts; && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // If we're looking up a local name to reference directly, omit namespace reexports, otherwise when we're trawling through an export list to make a dotted name, we can keep it + && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */))) { @@ -48302,7 +48549,7 @@ var ts; return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -48563,7 +48810,7 @@ var ts; return flags & 814775659 /* NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { - return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */)); + return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* Object */) && !!(ts.getObjectFlags(type) & 16777216 /* IsClassInstanceClone */))); } function createNodeBuilder() { return { @@ -49176,7 +49423,7 @@ var ts; } if (resolvedType.stringIndexInfo) { var indexSignature = void 0; - if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + if (resolvedType.objectFlags & 1024 /* ReverseMapped */) { indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context)); } else { @@ -49220,10 +49467,23 @@ var ts; } return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + // Use placeholders for reverse mapped types we've either already descended into, or which + // are nested reverse mappings within a mapping over a non-anonymous type. The later is a restriction mostly just to + // reduce the blowup in printback size from doing, eg, a deep reverse mapping over `Window`. + // Since anonymous types usually come from expressions, this allows us to preserve the output + // for deep mappings which likely come from expressions, while truncating those parts which + // come from mappings over library functions. + return !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) + && (ts.contains(context.reverseMappedStack, propertySymbol) + || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0]) + && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16 /* Anonymous */))); + } function addPropertyToElementList(propertySymbol, context, typeElements) { var _a; var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */); - var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; @@ -49255,16 +49515,20 @@ var ts; } } else { - var savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; var propertyTypeNode = void 0; - if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } } - context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; @@ -49305,25 +49569,25 @@ var ts; var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); /** Map from type reference identifier text to [type, index in `result` where the type node is] */ var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; - var result_4 = []; + var result_5 = []; var i = 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result_4.push(typeNode_1); + result_5.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result_4.push(typeNode); + result_5.push(typeNode); if (seenNames && ts.isIdentifierTypeReference(typeNode)) { - seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]); + seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]); } } } @@ -49345,13 +49609,13 @@ var ts; })) { for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var _a = types_3[_i], type = _a[0], resultIndex = _a[1]; - result_4[resultIndex] = typeToTypeNodeHelper(type, context); + result_5[resultIndex] = typeToTypeNodeHelper(type, context); } } }); context.flags = saveContextFlags; } - return result_4; + return result_5; } } function typesAreSameReference(a, b) { @@ -49685,7 +49949,7 @@ var ts; // specifier preference var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map()); links.specifierCache.set(contextFile.path, specifier); } @@ -49975,13 +50239,13 @@ var ts; function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { if (type !== errorType && enclosingDeclaration) { var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) { // try to reuse the existing annotation var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); - if (result_5) { - return result_5; + var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_6) { + return result_6; } } } @@ -49998,10 +50262,14 @@ var ts; function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { if (type !== errorType && context.enclosingDeclaration) { var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); - if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) { + var annotated = getTypeFromTypeNode(annotation); + var thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -51755,7 +52023,7 @@ var ts; var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= 131072 /* ObjectRestType */; + result.objectFlags |= 8388608 /* ObjectRestType */; return result; } function isGenericTypeWithUndefinedConstraint(type) { @@ -52063,6 +52331,22 @@ var ts; } ; } + /** Create a synthetic property access flow node after the last statement of the file */ + function getFlowTypeFromCommonJSExport(symbol) { + var file = ts.getSourceFileOfNode(symbol.declarations[0]); + var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName); + var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); }); + var reference = areAllModuleExports + ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName) + : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + ts.setParent(reference.expression.expression, reference.expression); + } + ts.setParent(reference.expression, reference); + ts.setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); + } function getFlowTypeInConstructor(symbol, constructor) { var accessName = ts.startsWith(symbol.escapedName, "__#") ? ts.factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) @@ -52178,7 +52462,7 @@ var ts; mergeSymbolTable(exports, s.exports); } var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - type.objectFlags |= 16384 /* JSLiteral */; + type.objectFlags |= 8192 /* JSLiteral */; return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { @@ -52279,9 +52563,9 @@ 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.stringIndexInfo, exportedType.numberIndexInfo); - result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + result.objectFlags |= (ts.getObjectFlags(type) & 8192 /* JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { - result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type + result.objectFlags |= 16777216 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type } return result; } @@ -52340,7 +52624,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -52364,7 +52648,7 @@ var ts; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -52383,7 +52667,7 @@ var ts; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -52640,38 +52924,31 @@ var ts; if (writing === void 0) { writing = false; } var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); // For write operations, prioritize type annotations on the setter - if (writing) { - var setterParameterType_1 = getAnnotatedAccessorType(setter); - if (setterParameterType_1) { - var flags = ts.getCheckFlags(symbol); - if (flags & 1 /* Instantiated */) { - var links = getSymbolLinks(symbol); - return instantiateType(setterParameterType_1, links.mapper); - } - return setterParameterType_1; - } + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); } // Else defer to the getter type if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } // Try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + var getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + if (setterType) { + return setterType; } // If there are no specified types, try to infer it from the body of the get accessor if it exists. if (getter && getter.body) { - return getReturnTypeFromBody(getter); + var returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); } // Otherwise, fall back to 'any'. if (setter) { @@ -52688,6 +52965,13 @@ var ts; return anyType; } return undefined; + function instantiateTypeIfNeeded(type, symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); + } + return type; + } } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); @@ -52752,14 +53036,16 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); + var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontResolveAlias*/ true); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 111551 /* Value */ - ? getTypeOfSymbol(targetSymbol) - : errorType; + links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -54363,6 +54649,12 @@ var ts; } } } + function replaceIndexedAccess(instantiable, type, replacement) { + // map type.indexType to 0 + // map type.objectType to `[TReplacement]` + // thus making the indexed access `[TReplacement][0]` or `TReplacement` + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } function getIndexInfoOfIndexSymbol(indexSymbol, indexKind) { var declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); if (!declaration) @@ -54383,8 +54675,21 @@ var ts; inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ + && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ + && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) { + // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is + // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of + // type identities produced, we simplify such indexed access occurences + var newTypeParam = type.constraintType.type.objectType; + var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.mappedType = newMappedType; + inferredProp.constraintType = getIndexType(newTypeParam); + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -54598,7 +54903,7 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 2048 /* ReverseMapped */) { + else if (type.objectFlags & 1024 /* ReverseMapped */) { resolveReverseMappedTypeMembers(type); } else if (type.objectFlags & 16 /* Anonymous */) { @@ -55017,6 +55322,7 @@ var ts; return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b; var singleProp; var propSet; var indexTypes; @@ -55025,8 +55331,9 @@ var ts; var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var current = _a[_i]; + var mergedInstantiations = false; + for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) { + var current = _c[_i]; var type = getApparentType(current); if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); @@ -55042,13 +55349,25 @@ var ts; singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new ts.Map(); - propSet.set(getSymbolId(singleProp), singleProp); + var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + // If the symbols are instances of one another with identical types - consider the symbols + // equivalent and just use the first one, which thus allows us to avoid eliding private + // members when intersecting a (this-)instantiations of a class with it's raw base or another instance + if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 /* True */ : 0 /* False */; }) === -1 /* True */) { + // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used + // to do when we recorded multiple distinct symbols so that we still get, eg, `Array.length` printed + // back and not `Array.length` when we're looking at a `.length` access on a `string[] | number[]` + mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - var id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new ts.Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + var id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | @@ -55066,7 +55385,7 @@ var ts; checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0); indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304 /* ContainsSpread */)) { checkFlags |= 32 /* WritePartial */; indexTypes = ts.append(indexTypes, undefinedType); } @@ -55082,7 +55401,19 @@ var ts; return undefined; } if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + // No symbol from a union/intersection should have a `.parent` set (since unions/intersections don't act as symbol parents) + // Unless that parent is "reconstituted" from the "first value declaration" on the symbol (which is likely different than its instantiated parent!) + // They also have a `.containingType` set, which affects some services endpoints behavior, like `getRootSymbol` + var clone_1 = createSymbolWithType(singleProp, singleProp.type); + clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent; + clone_1.containingType = containingType; + clone_1.mapper = singleProp.mapper; + return clone_1; + } + else { + return singleProp; + } } var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; @@ -55091,8 +55422,8 @@ var ts; var propTypes = []; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; - for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { - var prop = props_1[_b]; + for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { + var prop = props_1[_d]; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } @@ -55169,15 +55500,15 @@ var ts; * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. */ function getReducedType(type) { - if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 67108864 /* ContainsIntersections */) { return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); } else if (type.flags & 2097152 /* Intersection */) { - if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { - type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); + if (!(type.objectFlags & 67108864 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 67108864 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 134217728 /* IsNeverIntersection */ : 0); } - return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + return type.objectFlags & 134217728 /* IsNeverIntersection */ ? neverType : type; } return type; } @@ -55207,7 +55538,7 @@ var ts; return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); } function elaborateNeverIntersection(errorInfo, type) { - if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + if (type.flags & 2097152 /* Intersection */ && ts.getObjectFlags(type) & 134217728 /* IsNeverIntersection */) { var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); @@ -55364,6 +55695,9 @@ var ts; } return false; } + function isOptionalPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && node.questionToken; + } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; @@ -55518,8 +55852,7 @@ var ts; if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) return undefined; var typeTag = ts.getJSDocTypeTag(node); - var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); @@ -55884,6 +56217,17 @@ var ts; else if (grandParent.kind === 160 /* TypeParameter */ && grandParent.parent.kind === 191 /* MappedType */) { inferences = ts.append(inferences, keyofConstraintType); } + // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends + // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template + // of the check type's mapped type + else if (grandParent.kind === 191 /* MappedType */ && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 185 /* ConditionalType */ && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 191 /* MappedType */ && + grandParent.parent.checkType.type) { + var checkMappedType_1 = grandParent.parent.checkType; + var nodeType = getTypeFromTypeNode(checkMappedType_1.type); + inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); + } } } } @@ -55957,7 +56301,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 3670016 /* PropagatingFlags */; + return result & 917504 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -56086,11 +56430,21 @@ var ts; ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } + // We refrain from associating a local type alias with an instantiation of a top-level type alias + // because the local alias may end up being referenced in an inferred return type where it is not + // accessible--which in turn may lead to a large structural expansion of the type when generating + // a .d.ts file. See #43622 for an example. var aliasSymbol = getAliasSymbolForTypeNode(node); - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol) { + var _a; + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias); + return !!(declaration && ts.getContainingFunction(declaration)); + } function getTypeReferenceName(node) { switch (node.kind) { case 174 /* TypeReference */: @@ -56186,9 +56540,17 @@ var ts; } function getConditionalFlowTypeOfType(type, node) { var constraints; + var covariant = true; while (node && !ts.isStatement(node) && node.kind !== 312 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { + // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but + // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax + if (parent.kind === 161 /* Parameter */) { + covariant = !covariant; + } + // Always substitute on type parameters, regardless of variance, since even + // in contravariant positions, they may rely on substituted constraints to be valid + if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -56780,7 +57142,7 @@ var ts; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; } else { @@ -56982,8 +57344,8 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | - (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 67108864 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } function getUnionOrIntersectionTypePredicate(signatures, kind) { @@ -57041,7 +57403,7 @@ var ts; var typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id; + "#" + origin.type.id + "|" + getTypeListId(types); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { @@ -57168,7 +57530,7 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -57177,7 +57539,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -57206,7 +57568,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -57604,7 +57966,7 @@ var ts; if (noImplicitAny) { return false; // Flag is meaningless under `noImplicitAny` mode } - if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + if (ts.getObjectFlags(type) & 8192 /* JSLiteral */) { return true; } if (type.flags & 1048576 /* Union */) { @@ -57818,6 +58180,13 @@ var ts; } return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) { + type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ | + (isGenericObjectType(type.substitute) || isGenericObjectType(type.baseType) ? 8388608 /* IsGenericObjectType */ : 0); + } + return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); + } return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type) { @@ -57828,6 +58197,13 @@ var ts; } return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) { + type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ | + (isGenericIndexType(type.substitute) || isGenericIndexType(type.baseType) ? 33554432 /* IsGenericIndexType */ : 0); + } + return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); + } return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type); } function isThisTypeParameter(type) { @@ -58085,7 +58461,7 @@ var ts; // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { var isUnwrapped = isTypicalNondistributiveConditional(root); - var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { @@ -58098,7 +58474,7 @@ var ts; // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); } // It's possible for 'infer T' type paramteters to be given uninstantiated constraints when the // those type parameters are used in type references (see getInferredTypeParameterConstraint). For @@ -58355,7 +58731,7 @@ var ts; } } var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return spread; } } @@ -58461,7 +58837,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */ | 4194304 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ @@ -58881,8 +59257,9 @@ var ts; outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || ts.emptyArray; - typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? - ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) : + var allDeclarations_1 = type.objectFlags & 4 /* Reference */ ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) : typeParameters; links.outerTypeParameters = typeParameters; } @@ -58927,7 +59304,7 @@ var ts; return true; } } - return !!ts.forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node) { @@ -58939,6 +59316,9 @@ var ts; getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality case 177 /* TypeQuery */: return true; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + return (!node.type && !!node.body) || !!ts.forEachChild(node, containsReference); } return !!ts.forEachChild(node, containsReference); } @@ -59118,6 +59498,9 @@ var ts; var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; } + if (objectFlags & 1024 /* ReverseMapped */) { + return instantiateReverseMappedType(type, mapper); + } return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; @@ -59167,6 +59550,21 @@ var ts; } return type; } + function instantiateReverseMappedType(type, mapper) { + var innerMappedType = instantiateType(type.mappedType, mapper); + if (!(ts.getObjectFlags(innerMappedType) & 32 /* Mapped */)) { + return type; + } + var innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304 /* Index */)) { + return type; + } + var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); + if (instantiated) { + return instantiated; + } + return type; // Nested invocation of `inferTypeForHomomorphicMappedType` or the `source` instantiated into something unmappable + } function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -60082,7 +60480,7 @@ var ts; return false; } function isIgnoredJsxProperty(source, sourceProp) { - return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); + return ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { while (true) { @@ -60092,6 +60490,7 @@ var ts; type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; @@ -60409,7 +60808,7 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1 /* True */; } - reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */)); return 0 /* False */; } // Normalize the source and target types: Turn fresh literal types into regular literal types, @@ -60452,8 +60851,8 @@ var ts; if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); + var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -60538,7 +60937,7 @@ var ts; // We suppress recursive intersection property checks because they can generate lots of work when relating // recursive intersections that are structurally similar but not exactly identical. See #37854. if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); inPropertyCheck = false; @@ -60547,8 +60946,10 @@ var ts; return result; function reportErrorResults(source, target, result, isComparingJsxAttributes) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; var maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -60595,7 +60996,7 @@ var ts; if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { var sourceUnionOrIntersection = source; var targetUnionOrIntersection = target; - if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144 /* PrimitiveUnion */) { + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536 /* PrimitiveUnion */) { // There's a fast path for comparing primitive unions return; } @@ -60620,11 +61021,11 @@ var ts; } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & 3145728 /* UnionOrIntersection */) { - var result_6 = eachTypeRelatedToSomeType(source, target); - if (result_6) { - result_6 &= eachTypeRelatedToSomeType(target, source); + var result_7 = eachTypeRelatedToSomeType(source, target); + if (result_7) { + result_7 &= eachTypeRelatedToSomeType(target, source); } - return result_6; + return result_7; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -60639,10 +61040,10 @@ var ts; } function hasExcessProperties(source, target, reportErrors) { var _a; - if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; @@ -61056,21 +61457,21 @@ var ts; if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_7 = 0 /* False */; + var result_8 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_8; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_8; } } } @@ -61150,6 +61551,20 @@ var ts; } } else if (target.flags & 8388608 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { + // Relate components directly before falling back to constraint relationships + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } // A type S is related to a type T[K] if S is related to C, where C is the base // constraint of T[K] for writing. if (relation === assignableRelation || relation === comparableRelation) { @@ -61160,11 +61575,24 @@ var ts; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0); var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + // create a new chain for the constraint error + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { // A source type T is related to a target type { [P in X]: T[P] } @@ -61242,23 +61670,14 @@ var ts; // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - var result_8 = inferTypesFromTemplateLiteralType(source, target); - if (result_8 && ts.every(result_8, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + var result_9 = inferTypesFromTemplateLiteralType(source, target); + if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { return -1 /* True */; } } if (source.flags & 8650752 /* TypeVariable */) { - if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { - // A type S[K] is related to a type T[J] if S is related to T and K is related to J. - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - result &= isRelatedTo(source.indexType, target.indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - else { + // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch + if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) { var constraint = getConstraintOfType(source); if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. @@ -61273,7 +61692,7 @@ var ts; 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, reportErrors, /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -61285,6 +61704,16 @@ var ts; return result; } } + else if (source.flags & 134217728 /* TemplateLiteral */) { + if (!(target.flags & 134217728 /* TemplateLiteral */)) { + var baseConstraint = getBaseConstraintOfType(source); + var constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; + } + } + } else if (source.flags & 268435456 /* StringMapping */) { if (target.flags & 268435456 /* StringMapping */ && source.symbol === target.symbol) { if (result = isRelatedTo(source.type, target.type, reportErrors)) { @@ -61311,7 +61740,7 @@ var ts; if (sourceParams) { // If the source has infer type parameters, we instantiate them in the context of the target var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } @@ -61369,7 +61798,7 @@ var ts; return 0 /* False */; } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && - !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + !(ts.getObjectFlags(source) & 4096 /* MarkerType */ || ts.getObjectFlags(target) & 4096 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. @@ -61397,7 +61826,7 @@ var ts; } // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})` // and not `{} <- fresh({}) <- {[idx: string]: any}` - else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) { + else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 /* FreshLiteral */ && !isEmptyObjectType(source)) { return 0 /* False */; } // Even if relationship doesn't hold for unions, intersections, or generic type references, @@ -61435,14 +61864,19 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_9) { - return result_9; + var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_10) { + return result_10; } } } } return 0 /* False */; + function countMessageChainBreadth(info) { + if (!info) + return 0; + return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0); + } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -61504,13 +61938,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_10; + var result_11; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } } @@ -61650,7 +62084,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_11 = unionParent ? 0 /* False */ : -1 /* True */; + var result_12 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -61660,7 +62094,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_11 &= related; + result_12 &= related; } else { if (related) { @@ -61668,17 +62102,17 @@ var ts; } } } - if (unionParent && !result_11 && targetIsOptional) { - result_11 = isRelatedTo(source, undefinedType); + if (unionParent && !result_12 && targetIsOptional) { + result_12 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_11 && reportErrors) { + if (unionParent && !result_12 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_11; + return result_12; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); @@ -62280,7 +62714,7 @@ var ts; // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); - result.objectFlags |= 8192 /* MarkerType */; + result.objectFlags |= 4096 /* MarkerType */; return result; } function getAliasVariances(symbol) { @@ -62454,8 +62888,8 @@ var ts; } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. - function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons @@ -62473,23 +62907,26 @@ var ts; function isDeeplyNestedType(type, stack, depth) { if (depth >= 5) { var identity_1 = getRecursionIdentity(type); - if (identity_1) { - var count = 0; - for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= 5) { - return true; - } + var count = 0; + for (var i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity_1) { + count++; + if (count >= 5) { + return true; } } } } return false; } - // Types with constituents that could circularly reference the type have a recursion identity. The recursion - // identity is some object that is common to instantiations of the type with the same origin. + // The recursion identity of a type is an object identity that is shared among multiple instantiations of the type. + // We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with + // the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all + // instantiations of that type have the same recursion identity. The default recursion identity is the object + // identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly + // reference the type have a recursion identity that differs from the object identity. function getRecursionIdentity(type) { + // Object and array literals are known not to contain recursive references and don't need a recursion identity. if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) { // Deferred type references are tracked through their associated AST node. This gives us finer @@ -62507,6 +62944,9 @@ var ts; return type.target; } } + if (type.flags & 262144 /* TypeParameter */) { + return type.symbol; + } if (type.flags & 8388608 /* IndexedAccess */) { // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A do { @@ -62518,7 +62958,7 @@ var ts; // The root object represents the origin of the conditional type return type.root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; @@ -62656,6 +63096,9 @@ var ts; // 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; }); @@ -62688,12 +63131,30 @@ var ts; function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return isArrayType(type) || hasArrayOrReadonlyArrayBaseType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } - function hasArrayOrReadonlyArrayBaseType(type) { - return !!(ts.getObjectFlags(type) & 4 /* Reference */) - && !!(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */) - && ts.some(getBaseTypes(type.target), isArrayType); + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */)) { + return undefined; + } + if (ts.getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) { + return ts.getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : undefined; + } + type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */; + var target = type.target; + var bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; // If the interface has any members, they may subtype members in the base, so we should do a full structural comparison + } + var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type))); + } + type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */; + return type.cachedEquivalentBaseType = instantiatedBase; } function isEmptyArrayLiteralType(type) { var elementType = getElementTypeOfArrayType(type); @@ -62938,7 +63399,7 @@ var ts; function isObjectTypeWithInferableIndex(type) { return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */); @@ -62971,7 +63432,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -62982,7 +63443,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */; + regularNew.objectFlags |= resolved.objectFlags & ~16384 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -63012,7 +63473,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; - if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304 /* ContainsSpread */)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; names.set(prop.escapedName, prop); @@ -63061,14 +63522,14 @@ var ts; var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (8192 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -63113,7 +63574,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -63139,7 +63600,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -63219,7 +63680,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -63335,16 +63796,16 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) { - return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); + if (objectFlags & 1048576 /* CouldContainTypeVariablesComputed */) { + return !!(objectFlags & 2097152 /* CouldContainTypeVariables */); } var result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 8388608 /* ObjectRestType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { - type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); + type.objectFlags |= 1048576 /* CouldContainTypeVariablesComputed */ | (result ? 2097152 /* CouldContainTypeVariables */ : 0); } return result; } @@ -63404,7 +63865,7 @@ var ts; // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive // arrow function, but is considered partially inferable because property 'a' has an inferable type. function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 524288 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) || isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType); } @@ -63428,14 +63889,18 @@ var ts; } // For all other object types we infer a new object type where the reverse mapping has been // applied to the type of each property. - var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + var reversed = createObjectType(1024 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType, target, constraint) { var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); @@ -63633,7 +64098,7 @@ var ts; if (contravariant === void 0) { contravariant = false; } var bivariant = false; var propagationType; - var inferencePriority = 1024 /* MaxValue */; + var inferencePriority = 2048 /* MaxValue */; var allowComplexConstraintInference = true; var visited; var sourceStack; @@ -63720,8 +64185,8 @@ var ts; // 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 (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || - (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || + (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -63748,7 +64213,7 @@ var ts; clearCachedInferences(inferences); } } - if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -63788,7 +64253,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - inferWithPriority(empty, target.type, 128 /* LiteralKeyof */); + inferWithPriority(empty, target.type, 256 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -63800,6 +64265,13 @@ var ts; inferFromTypes(source.type, target.type); } } + else if (source.flags & 33554432 /* Substitution */) { + inferFromTypes(source.baseType, target); + var oldPriority = priority; + priority |= 4 /* SubstituteSource */; + inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority + priority = oldPriority; + } else if (target.flags & 16777216 /* Conditional */) { invokeOnce(source, target, inferToConditionalType); } @@ -63819,7 +64291,7 @@ var ts; } else { source = getReducedType(source); - if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { + if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` @@ -63857,26 +64329,22 @@ var ts; } (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */); var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; // We stop inferring and report a circularity if we encounter duplicate recursion identities on both // the source side and the target side. var saveExpandingFlags = expandingFlags; - var sourceIdentity = getRecursionIdentity(source) || source; - var targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && ts.contains(sourceStack, sourceIdentity)) + var sourceIdentity = getRecursionIdentity(source); + var targetIdentity = getRecursionIdentity(target); + if (ts.contains(sourceStack, sourceIdentity)) expandingFlags |= 1 /* Source */; - if (targetIdentity && ts.contains(targetStack, targetIdentity)) + if (ts.contains(targetStack, targetIdentity)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { - if (sourceIdentity) - (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) - (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) - targetStack.pop(); - if (sourceIdentity) - sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = -1 /* Circularity */; @@ -63916,7 +64384,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -63968,7 +64436,7 @@ var ts; else { for (var i = 0; i < sources.length; i++) { var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; inferFromTypes(sources[i], t); if (inferencePriority === priority) matched_1[i] = true; @@ -64047,7 +64515,7 @@ var ts; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? 8 /* PartialHomomorphicMappedType */ : 4 /* HomomorphicMappedType */); + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 /* NonInferrableType */ ? 16 /* PartialHomomorphicMappedType */ : 8 /* HomomorphicMappedType */); } } return true; @@ -64055,7 +64523,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */); + inferWithPriority(getIndexType(source), constraintType, 32 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -64084,7 +64552,7 @@ var ts; } else { var savePriority = priority; - priority |= contravariant ? 32 /* ContravariantConditional */ : 0; + priority |= contravariant ? 64 /* ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, target.flags); priority = savePriority; @@ -64207,7 +64675,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -64258,7 +64726,7 @@ var ts; return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); } function isObjectOrArrayLiteralType(type) { - return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */)); + return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 32768 /* ArrayLiteral */)); } function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { @@ -64271,7 +64739,7 @@ var ts; return candidates; } function getContravariantInference(inference) { - return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } function getCovariantInference(inference, signature) { // Extract all object and array literal types and replace them with a single widened and normalized type. @@ -64288,7 +64756,7 @@ var ts; candidates; // If all inferences were made from a position that implies a combined result, infer a union type. // Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ? + var unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -64585,14 +65053,14 @@ var ts; function getKeyPropertyName(unionType) { var types = unionType.types; // We only construct maps for large unions with non-primitive constituents. - if (types.length < 10 || ts.getObjectFlags(unionType) & 262144 /* PrimitiveUnion */) { + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { return undefined; } if (unionType.keyPropertyName === undefined) { // The candidate key property name is the name of the first property with a unit type in one of the // constituent types. var keyPropertyName = ts.forEach(types, function (t) { - return t.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? + return t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) : undefined; }); @@ -64687,7 +65155,8 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, ignoreObjects) { + if (ignoreObjects === void 0) { ignoreObjects = false; } var flags = type.flags; if (flags & 4 /* String */) { return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; @@ -64724,7 +65193,7 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 524288 /* Object */) { + if (flags & 524288 /* Object */ && !ignoreObjects) { return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? @@ -64747,14 +65216,17 @@ var ts; return 0 /* None */; } if (flags & 465829888 /* Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */; } if (flags & 1048576 /* Union */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t); }, 0 /* None */); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* None */); } if (flags & 2097152 /* Intersection */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t); }, 16777215 /* All */); + // 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 /* Primitive */)); + return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */); } return 16777215 /* All */; } @@ -64963,6 +65435,9 @@ var ts; function everyType(type, f) { return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } + function everyContainedType(type, f) { + return type.flags & 3145728 /* UnionOrIntersection */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 1048576 /* Union */) { var types = type.types; @@ -66263,7 +66738,16 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); + return filterType(type, function (t) { + if (!isRelated(t, candidate)) { + return true; + } + var constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } // 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. @@ -66358,17 +66842,20 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 78 /* Identifier */) { + if (location.kind === 78 /* Identifier */ || location.kind === 79 /* PrivateIdentifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true); + } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the @@ -66493,7 +66980,6 @@ var ts; } } function checkIdentifier(node, checkMode) { - var _a; var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -66595,7 +67081,7 @@ var ts; } } else if (isAlias) { - declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -66808,7 +67294,7 @@ var ts; break; case 164 /* PropertyDeclaration */: case 163 /* PropertySignature */: - if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } @@ -67451,16 +67937,16 @@ var ts; // In an assignment expression, the right operand is contextually typed by the type of the left operand. // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return getTypeOfExpression(binaryExpression.left); + case 4 /* ThisProperty */: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case 5 /* Property */: - case 1 /* ExportsProperty */: - case 6 /* Prototype */: - case 3 /* PrototypeProperty */: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. @@ -67481,11 +67967,11 @@ var ts; var id = lhs.expression; var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true); if (parentSymbol) { - var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); - if (annotated) { + var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated_1) { var nameStr = ts.getElementOrPropertyAccessName(lhs); if (nameStr !== undefined) { - return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr); + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr); } } return undefined; @@ -67493,9 +67979,15 @@ var ts; } return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; + // falls through case 2 /* ModuleExports */: - case 4 /* ThisProperty */: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); + var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case 7 /* ObjectDefinePropertyValue */: case 8 /* ObjectDefinePropertyExports */: case 9 /* ObjectDefinePrototypeProperty */: @@ -67516,7 +68008,7 @@ var ts; var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true); return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) { + function getContextualTypeForThisPropertyAssignment(binaryExpression) { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { @@ -67528,8 +68020,6 @@ var ts; } } } - if (kind === 2 /* ModuleExports */) - return undefined; var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression); if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return undefined; @@ -67584,6 +68074,10 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { if (hasBindableName(element)) { @@ -67681,10 +68175,10 @@ var ts; return false; } function discriminateContextualTypeByObjectMembers(node, contextualType) { - return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -67793,7 +68287,7 @@ var ts; case 290 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent, contextFlags); case 291 /* SpreadAssignment */: - return getApparentTypeOfContextualType(parent.parent, contextFlags); + return getContextualType(parent.parent, contextFlags); case 200 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); @@ -68189,7 +68683,7 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 32768 /* ArrayLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; } return literalType; } @@ -68346,7 +68840,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -68474,9 +68968,9 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { - result.objectFlags |= 16384 /* JSLiteral */; + result.objectFlags |= 8192 /* JSLiteral */; } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -68566,14 +69060,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var objectFlags = 4096 /* JsxAttributes */; + var objectFlags = 2048 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -68657,7 +69151,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -69159,7 +69653,7 @@ var ts; // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { @@ -69334,6 +69828,23 @@ var ts; if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); } + if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (compilerOptions.target === 99 /* ESNext */ && !useDefineForClassFields)) { + var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); + var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { + if (n === lexicalClass_1) + return "quit"; + if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); + } + } if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -69423,7 +69934,10 @@ var ts; // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + prop && + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) + && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { @@ -69466,6 +69980,7 @@ var ts; var diagnosticMessage; var declarationName = ts.idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { @@ -69571,7 +70086,10 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + var diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : ts.Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -69582,6 +70100,11 @@ var ts; } diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) && + isEmptyObjectType(containingType); + } function typeHasStaticProperty(propName, containingType) { var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); return prop !== undefined && !!prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); @@ -70048,7 +70571,7 @@ var ts; }); if (!inferenceContext) { applyToReturnTypes(contextualSignature, signature, function (source, target) { - inferTypes(context.inferences, source, target, 64 /* ReturnType */); + inferTypes(context.inferences, source, target, 128 /* ReturnType */); }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); @@ -70098,7 +70621,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* 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 @@ -70543,77 +71066,66 @@ var ts; return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - var belowArgCount = Number.NEGATIVE_INFINITY; - var aboveArgCount = Number.POSITIVE_INFINITY; - var argCount = args.length; + var _a; + var spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } + var min = Number.POSITIVE_INFINITY; // smallest parameter count + var max = Number.NEGATIVE_INFINITY; // largest parameter count + var maxBelow = Number.NEGATIVE_INFINITY; // largest parameter count that is smaller than the number of arguments + var minAbove = Number.POSITIVE_INFINITY; // smallest parameter count that is larger than the number of arguments var closestSignature; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var sig = signatures_8[_i]; - var minCount = getMinArgumentCount(sig); - var maxCount = getParameterCount(sig); - if (minCount < argCount && minCount > belowArgCount) - belowArgCount = minCount; - if (argCount < maxCount && maxCount < aboveArgCount) - aboveArgCount = maxCount; - if (minCount < min) { - min = minCount; + var minParameter = getMinArgumentCount(sig); + var maxParameter = getParameterCount(sig); + // smallest/largest parameter counts + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + max = Math.max(max, maxParameter); + // shortest parameter count *longer than the call*/longest parameter count *shorter than the call* + if (minParameter < args.length && minParameter > maxBelow) + maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) + minAbove = maxParameter; } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); - var paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var spanArray; - var related; - var error = hasRestParameter || hasSpreadArgument ? - hasRestParameter && hasSpreadArgument ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - ts.Diagnostics.Expected_0_arguments_but_got_1; - if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { - var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; - if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : - ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); - } - } - if (!hasSpreadArgument && argCount < min) { - var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } - if (hasRestParameter || hasSpreadArgument) { - spanArray = ts.factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); + var parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : ts.Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + // between min and max, but with no matching overload + return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + // too short: put the error span on the call expression, not any of the args + var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined); + return ts.addRelatedInfo(diagnostic, parameterError); } + return diagnostic; } else { - spanArray = ts.factory.createNodeArray(args.slice(max)); - } - var pos = ts.first(spanArray).pos; - var end = ts.last(spanArray).end; - if (end === pos) { - end++; + // too long; error goes on the excess parameters + var errorSpan = ts.factory.createNodeArray(args.slice(max)); + var pos = ts.first(errorSpan).pos; + var end = ts.last(errorSpan).end; + if (end === pos) { + end++; + } + ts.setTextRangePosEnd(errorSpan, pos, end); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - ts.setTextRangePosEnd(spanArray, pos, end); - var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -71706,7 +72218,7 @@ var ts; var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false); if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) { var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + jsAssignmentType.objectFlags |= 8192 /* JSLiteral */; return getIntersectionType([returnType, jsAssignmentType]); } } @@ -72138,7 +72650,14 @@ var ts; } } function assignContextualParameterTypes(signature, context) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; // This signature has already has a contextual inference performed and cached on it! + } + } if (context.thisParameter) { var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { @@ -72531,17 +73050,17 @@ var ts; return; } var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */; + var errorNode = ts.getEffectiveReturnTypeNode(func) || func; if (type && type.flags & 131072 /* Never */) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { // minimal check: function has syntactic return type annotation and no explicit return statements in the body // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -72556,7 +73075,7 @@ var ts; return; } } - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { @@ -72576,7 +73095,7 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; + returnOnlyType.objectFlags |= 524288 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } } @@ -74377,7 +74896,7 @@ var ts; checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { if (!(func.kind === 167 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } @@ -74834,9 +75353,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); })); + ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -74888,15 +75407,18 @@ var ts; var symbol = getSymbolOfNode(node); var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); - if (getter && setter) { + if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) { + getNodeLinks(getter).flags |= 1 /* TypeChecked */; var getterFlags = ts.getEffectiveModifierFlags(getter); var setterFlags = ts.getEffectiveModifierFlags(setter); if ((getterFlags & 128 /* Abstract */) !== (setterFlags & 128 /* Abstract */)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } if (((getterFlags & 16 /* Protected */) && !(setterFlags & (16 /* Protected */ | 8 /* Private */))) || ((getterFlags & 8 /* Private */) && !(setterFlags & 8 /* Private */))) { - error(node.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } var getterType = getAnnotatedAccessorType(getter); var setterType = getAnnotatedAccessorType(setter); @@ -75456,20 +75978,23 @@ var ts; case 298 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: + var node_2 = d; + var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values - if (!ts.isEntityNameExpression(d.expression)) { + if (!ts.isEntityNameExpression(expression)) { return 1 /* ExportValue */; } - d = d.expression; + d = expression; // The below options all declare an Alias, which is allowed to merge with other values within the importing module. // falls through case 261 /* ImportEqualsDeclaration */: case 264 /* NamespaceImport */: case 263 /* ImportClause */: - var result_12 = 0 /* None */; + var result_13 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); - return result_12; + ts.forEach(target.declarations, function (d) { result_13 |= getDeclarationSpaces(d); }); + return result_13; case 250 /* VariableDeclaration */: case 199 /* BindingElement */: case 252 /* FunctionDeclaration */: @@ -76790,11 +77315,6 @@ var ts; return; if (getFalsyFlags(type)) return; - if (getAwaitedTypeOfPromise(type)) { - errorAndMaybeSuggestAwait(condExpr, - /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined, getTypeNameForErrorDisplay(type)); - return; - } var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr; var testedNode = ts.isIdentifier(location) ? location : ts.isPropertyAccessExpression(location) ? location.name @@ -76806,25 +77326,32 @@ var ts; return; } // While it technically should be invalid for any known-truthy value - // to be tested, we de-scope to functions unrefenced in the block as a - // heuristic to identify the most common bugs. There are too many - // false positives for values sourced from type definitions without - // strictNullChecks otherwise. + // to be tested, we de-scope to functions and Promises unreferenced in + // the block as a heuristic to identify the most common bugs. There + // are too many false positives for values sourced from type + // definitions without strictNullChecks otherwise. var callSignatures = getSignaturesOfType(type, 0 /* Call */); - if (callSignatures.length === 0) { + var isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } var testedSymbol = getSymbolAtLocation(testedNode); if (!testedSymbol) { return; } - var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + var isUsed = ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait(location, + /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); + } + else { + error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) { + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { return !!ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); @@ -76861,7 +77388,7 @@ var ts; return ts.forEachChild(childNode, check); }); } - function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) { + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { var isUsed = ts.forEachChild(node.right, function visit(child) { if (ts.isIdentifier(child)) { @@ -78184,7 +78711,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - checkMembersForMissingOverrideModifier(node, type, typeWithThis); + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -78219,12 +78746,16 @@ var ts; checkPropertyInitialization(node); } } - function checkMembersForMissingOverrideModifier(node, type, typeWithThis) { + function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); var baseTypeNode = ts.getEffectiveBaseTypeNode(node); var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); var _loop_24 = function (member) { + if (ts.hasAmbientModifier(member)) { + return "continue"; + } if (ts.isConstructorDeclaration(member)) { ts.forEach(member.parameters, function (param) { if (ts.isParameterPropertyDeclaration(param, member)) { @@ -78240,14 +78771,17 @@ var ts; } function checkClassMember(member, memberIsParameterProperty) { var hasOverride = ts.hasOverrideModifier(member); + var hasStatic = ts.hasStaticModifier(member); if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); if (!declaredProp) { return; } + var thisType = hasStatic ? staticType : typeWithThis; + var baseType = hasStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); var baseClassName = typeToString(baseWithThis); - var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); - var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && !baseProp && hasOverride) { error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } @@ -78258,7 +78792,7 @@ var ts; } if (!baseHasAbstract) { var diag = memberIsParameterProperty ? - ts.Diagnostics.This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; error(member, diag, baseClassName); } @@ -78412,7 +78946,7 @@ var ts; ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { + else if (useDefineForClassFields) { var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 164 /* PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* Transient */) @@ -79288,7 +79822,10 @@ var ts; } } function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + var illegalContextMessage = node.isExportEquals + ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } @@ -79377,10 +79914,12 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, _b = declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (var _i = 0, _b = declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } } @@ -79389,6 +79928,11 @@ var ts; links.exportsChecked = true; } } + function isDuplicatedCommonJSExport(declarations) { + return declarations + && declarations.length > 1 + && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); }); + } function checkSourceElement(node) { if (node) { var saveCurrentNode = currentNode; @@ -79619,7 +80163,8 @@ var ts; if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_1) { + var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent); + if (host_1 || isCallbackTag) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -79627,7 +80172,9 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var lastParamDeclaration = isCallbackTag + ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) + : ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -79843,11 +80390,11 @@ var ts; } switch (location.kind) { case 298 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) + if (!ts.isExternalModule(location)) break; // falls through case 257 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; case 256 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); @@ -79910,6 +80457,16 @@ var ts; }); } } + function copyLocallyVisibleExportSymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + // Similar condition as in `resolveNameHelper` + if (!ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 270 /* NamespaceExport */)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name) { return name.kind === 78 /* Identifier */ && @@ -79949,14 +80506,14 @@ var ts; } return node.parent.kind === 224 /* ExpressionWithTypeArguments */; } - function isJSDocEntryNameReference(node) { + function getJSDocEntryNameReference(node) { while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 303 /* JSDocNameReference */; + return ts.isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node, callback) { var result; @@ -80118,18 +80675,34 @@ var ts; var meaning = name.parent.kind === 174 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (isJSDocEntryNameReference(name)) { - var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); - } - else if (ts.isJSDocLink(name.parent)) { + var jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || ts.isJSDocLink(name.parent)) { var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ true); + var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ false, ts.getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (ts.isQualifiedName(name) && ts.isIdentifier(name.left)) { + // resolve C.m as a static member first + var links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, 0 /* Normal */); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + // then resolve it as an instance member + var s = resolveEntityName(name.left, meaning, /*ignoreErrors*/ false); + if (s) { + var t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } } if (name.parent.kind === 173 /* TypePredicate */) { return resolveEntityName(name, 1 /* FunctionScopedVariable */); } - // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node, ignoreErrors) { @@ -80329,10 +80902,10 @@ var ts; // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { if (expr.parent.kind === 289 /* PropertyAssignment */) { - var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); - var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType; - var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent); - return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex); + var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); + var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; + var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex); } // Array literal assignment - array destructuring pattern var node = ts.cast(expr.parent, ts.isArrayLiteralExpression); @@ -80686,13 +81259,13 @@ var ts; !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && !!parameter.initializer && - !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + !ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameter(parameter) { return !!strictNullChecks && @@ -81400,17 +81973,18 @@ var ts; } break; case 156 /* OverrideKeyword */: + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override"); } else if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); } - else if (flags & 32 /* Static */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "override"); + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); } - if (node.kind === 161 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "override"); + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); } flags |= 16384 /* Override */; lastOverride = modifier; @@ -81422,7 +81996,7 @@ var ts; if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + else if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); } else if (flags & 32 /* Static */) { @@ -81457,9 +82031,6 @@ var ts; else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "override"); - } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } @@ -81472,6 +82043,9 @@ var ts; else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); + } flags |= 32 /* Static */; lastStatic = modifier; break; @@ -81480,7 +82054,7 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } else if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */ && node.kind !== 172 /* IndexSignature */ && node.kind !== 161 /* Parameter */) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; @@ -81521,7 +82095,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + else if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); } else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { @@ -81563,6 +82137,9 @@ var ts; if (flags & 256 /* Async */ && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -81594,7 +82171,7 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } - if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + if (flags & 16384 /* Override */) { return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 } else if (flags & 256 /* Async */) { @@ -81608,10 +82185,10 @@ var ts; else if ((node.kind === 262 /* ImportDeclaration */ || node.kind === 261 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 161 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 161 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -82895,20 +83472,6 @@ var ts; return ts.isDeclarationName(name); } } - function isSomeImportDeclaration(decl) { - switch (decl.kind) { - case 263 /* ImportClause */: // For default import - case 261 /* ImportEqualsDeclaration */: - case 264 /* NamespaceImport */: - case 266 /* ImportSpecifier */: - return true; - case 78 /* Identifier */: - // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 266 /* ImportSpecifier */; - default: - return false; - } - } var JsxNames; (function (JsxNames) { JsxNames.JSX = "JSX"; @@ -87778,10 +88341,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_1 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_1, node); - ts.setCommentRange(clone_1, node); - return clone_1; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -87866,6 +88429,7 @@ var ts; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var shouldTransformPrivateElements = languageVersion < 99 /* ESNext */; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; @@ -87887,7 +88451,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === 99 /* ESNext */) { + || useDefineForClassFields && options.target === 99 /* ESNext */) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -88046,7 +88610,7 @@ var ts; // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } @@ -88357,7 +88921,7 @@ var ts; if (ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. return languageVersion < 99 /* ESNext */; @@ -88380,7 +88944,6 @@ var ts; /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); @@ -88492,7 +89055,7 @@ var ts; function transformProperty(property, receiver) { var _a; // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) - var emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + var emitAssignment = !useDefineForClassFields; var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; @@ -88597,10 +89160,10 @@ var ts; 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; + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; } } } @@ -90762,9 +91325,9 @@ var ts; function convertJsxChildrenToChildrenPropObject(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) + var result_14 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_14 && factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("children", result_14) ]); } var result = ts.mapDefined(children, transformJsxChildToExpression); @@ -92496,7 +93059,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName); var e; - if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) { var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; @@ -93319,13 +93882,13 @@ var ts; loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); - loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); + loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { - var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; @@ -96271,10 +96834,10 @@ var ts; var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { // TODO(rbuckton): Does this need to be parented? - var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); - ts.setSourceMapRange(clone_5, node); - ts.setCommentRange(clone_5, node); - return clone_5; + var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -97268,8 +97831,6 @@ var ts; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(204 /* CallExpression */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(206 /* TaggedTemplateExpression */); // Substitutes expression identifiers with imported/exported symbols. context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. @@ -97280,7 +97841,6 @@ var ts; var currentModuleInfo; // The ExternalModuleInfo for the current file. var noSubstitution; // Set of nodes for which substitution rules should be ignored. var needUMDDynamicImportHelper; - var bindingReferenceCache; return ts.chainBundle(context, transformSourceFile); /** * Transforms the module aspects of a SourceFile. @@ -98527,10 +99087,6 @@ var ts; return substituteExpressionIdentifier(node); case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 204 /* CallExpression */: - return substituteCallExpression(node); - case 206 /* TaggedTemplateExpression */: - return substituteTaggedTemplateExpression(node); case 216 /* PostfixUnaryExpression */: case 215 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); @@ -98538,99 +99094,41 @@ var ts; return node; } /** - * For an Identifier, gets the import or export binding that it references. - * @returns One of the following: - * - An `Identifier` if node references an external helpers module (i.e., `tslib`). - * - A `SourceFile` if the node references an export in the file. - * - An `ImportClause` or `ImportSpecifier` if the node references an import binding. - * - Otherwise, `undefined`. + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. */ - function getImportOrExportBindingReferenceWorker(node) { + function substituteExpressionIdentifier(node) { + var _a, _b; if (ts.getEmitFlags(node) & 4096 /* HelperName */) { var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); if (externalHelpersModuleName) { - return externalHelpersModuleName; + return factory.createPropertyAccessExpression(externalHelpersModuleName, node); } + return node; } else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if ((exportContainer === null || exportContainer === void 0 ? void 0 : exportContainer.kind) === 298 /* SourceFile */) { - return exportContainer; + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { + return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), + /*location*/ node); } var importDeclaration = resolver.getReferencedImportDeclaration(node); - if (importDeclaration && (ts.isImportClause(importDeclaration) || ts.isImportSpecifier(importDeclaration))) { - return importDeclaration; - } - } - return undefined; - } - /** - * For an Identifier, gets the import or export binding that it references. - * @param removeEntry When `false`, the result is cached to avoid recomputing the result in a later substitution. - * When `true`, any cached result for the node is removed. - * @returns One of the following: - * - An `Identifier` if node references an external helpers module (i.e., `tslib`). - * - A `SourceFile` if the node references an export in the file. - * - An `ImportClause` or `ImportSpecifier` if the node references an import binding. - * - Otherwise, `undefined`. - */ - function getImportOrExportBindingReference(node, removeEntry) { - var result = bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.get(node); - if (!result && !(bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.has(node))) { - result = getImportOrExportBindingReferenceWorker(node); - if (!removeEntry) { - bindingReferenceCache || (bindingReferenceCache = new ts.Map()); - bindingReferenceCache.set(node, result); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || importDeclaration), factory.cloneNode(name)), + /*location*/ node); + } } } - else if (removeEntry) { - bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.delete(node); - } - return result; - } - function substituteCallExpression(node) { - if (ts.isIdentifier(node.expression) && getImportOrExportBindingReference(node.expression, /*removeEntry*/ false)) { - return ts.isCallChain(node) ? - factory.updateCallChain(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.expression), node.expression), node.questionDotToken, - /*typeArguments*/ undefined, node.arguments) : - factory.updateCallExpression(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.expression), node.expression), - /*typeArguments*/ undefined, node.arguments); - } return node; } - function substituteTaggedTemplateExpression(node) { - if (ts.isIdentifier(node.tag) && getImportOrExportBindingReference(node.tag, /*removeEntry*/ false)) { - return factory.updateTaggedTemplateExpression(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.tag), node.tag), - /*typeArguments*/ undefined, node.template); - } - return node; - } - /** - * Substitution for an Identifier expression that may contain an imported or exported - * symbol. - * - * @param node The node to substitute. - */ - function substituteExpressionIdentifier(node) { - var _a, _b; - var result = getImportOrExportBindingReference(node, /*removeEntry*/ true); - switch (result === null || result === void 0 ? void 0 : result.kind) { - case 78 /* Identifier */: - return factory.createPropertyAccessExpression(result, node); - case 298 /* SourceFile */: - return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), - /*location*/ node); - case 263 /* ImportClause */: - return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(result.parent), factory.createIdentifier("default")), - /*location*/ node); - case 266 /* ImportSpecifier */: - var name = result.propertyName || result.name; - return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = result.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || result), factory.cloneNode(name)), - /*location*/ node); - default: - return node; - } - } /** * Substitution for a BinaryExpression that may contain an imported or exported symbol. * @@ -99892,7 +100390,7 @@ var ts; return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } /** - * Determines whether the target of a destructuring assigment refers to an exported symbol. + * Determines whether the target of a destructuring assignment refers to an exported symbol. * * @param node The destructuring target. */ @@ -101076,7 +101574,7 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, + var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, /*preferences*/ undefined); if (!ts.pathIsRelative(specifier)) { // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration @@ -101822,7 +102320,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param)) + if (!ts.hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 78 /* Identifier */) { @@ -102607,32 +103105,32 @@ var ts; } ts.transformNodes = transformNodes; ts.nullTransformationContext = { - get factory() { return ts.factory; }, - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: ts.returnUndefined, + factory: ts.factory, getCompilerOptions: function () { return ({}); }, - getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + getEmitHost: ts.notImplemented, getEmitHelperFactory: ts.notImplemented, + startLexicalEnvironment: ts.noop, + resumeLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + endLexicalEnvironment: ts.returnUndefined, setLexicalEnvironmentFlags: ts.noop, getLexicalEnvironmentFlags: function () { return 0; }, - hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + hoistFunctionDeclaration: ts.noop, addInitializationStatement: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop, - addDiagnostic: ts.noop, startBlockScope: ts.noop, endBlockScope: ts.returnUndefined, - addBlockScopedVariable: ts.noop + addBlockScopedVariable: ts.noop, + requestEmitHelper: ts.noop, + readEmitHelpers: ts.notImplemented, + enableSubstitution: ts.noop, + enableEmitNotification: ts.noop, + isSubstitutionEnabled: ts.notImplemented, + isEmitNotificationEnabled: ts.notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, + addDiagnostic: ts.noop, }; })(ts || (ts = {})); var ts; @@ -103381,10 +103879,18 @@ var ts; return outputFiles; } ts.emitUsingBuildInfo = emitUsingBuildInfo; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); var moduleKind = ts.getEmitModuleKind(printerOptions); @@ -103423,8 +103929,10 @@ var ts; var detachedCommentsInfo; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; - var _a = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _a.enter, exitComment = _a.exit; - var preprint = createPreprinter(handlers); + var lastSubstitution; + var currentParenthesizerRule; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + var parenthesizer = ts.factory.parenthesizer; var emitBinaryExpression = createEmitBinaryExpression(); reset(); return { @@ -103624,7 +104132,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - emit(preprint(hint, node)); + pipelineEmit(hint, node, /*parenthesizerRule*/ undefined); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -103657,13 +104165,40 @@ var ts; function getCurrentLineMap() { return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } - function emit(node) { + function emit(node, parenthesizerRule) { if (node === undefined) return; var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - emitWithContext(node, emitWorker); + pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); } + function emitIdentifierName(node) { + if (node === undefined) + return; + pipelineEmit(2 /* IdentifierName */, node, /*parenthesizerRule*/ undefined); + } + function emitExpression(node, parenthesizerRule) { + if (node === undefined) + return; + pipelineEmit(1 /* Expression */, node, parenthesizerRule); + } + function emitJsxAttributeValue(node) { + pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); + } + function beforeEmitNode(node) { + if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { + preserveSourceNewlines = false; + } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; + var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); + pipelinePhase(emitHint, node); + currentParenthesizerRule = undefined; + } function shouldEmitComments(node) { return !commentsDisabled && !ts.isSourceFile(node); } @@ -103674,484 +104209,504 @@ var ts; !ts.isUnparsedSource(node) && !ts.isUnparsedPrepend(node); } - function beforeEmitWithContext(node, shouldEmitComments, shouldEmitSourceMaps) { - onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); - var emitFlags = ts.getEmitFlags(node); - var commentRange = shouldEmitComments ? ts.getCommentRange(node) : undefined; - var sourceMapRange = shouldEmitSourceMaps ? ts.getSourceMapRange(node) : undefined; - if (preserveSourceNewlines && (emitFlags & 134217728 /* IgnoreSourceNewlines */)) { - preserveSourceNewlines = false; - } - // Emit leading comments - if (commentRange) { - emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = true; - } - } - // Emit leading sourcemap - if (sourceMapRange) { - if (ts.isUnparsedNode(node)) { - ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); - var parsed = getParsedSourceMap(node.parent); - if (parsed && sourceMapGenerator) { - sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); + function getPipelinePhase(phase, emitHint, node) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { + return pipelineEmitWithNotification; } - } - else { - var source = sourceMapRange.source || sourceMapSource; - if (node.kind !== 339 /* NotEmittedStatement */ - && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && sourceMapRange.pos >= 0) { - emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + // falls through + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } + return pipelineEmitWithSubstitution; } - if (emitFlags & 64 /* NoNestedSourceMaps */) { - sourceMapsDisabled = true; + // falls through + case 2 /* Comments */: + if (shouldEmitComments(node)) { + return pipelineEmitWithComments; } - } + // falls through + case 3 /* SourceMaps */: + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; + } + // falls through + case 4 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase); } } - function afterEmitWithContext(node, shouldEmitComments, shouldEmitSourceMaps, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines) { - var emitFlags = ts.getEmitFlags(node); - var commentRange = shouldEmitComments ? ts.getCommentRange(node) : undefined; - var sourceMapRange = shouldEmitSourceMaps ? ts.getSourceMapRange(node) : undefined; - // Emit trailing sourcemap - if (sourceMapRange) { - if (!ts.isUnparsedNode(node)) { - if (emitFlags & 64 /* NoNestedSourceMaps */) { - sourceMapsDisabled = false; - } - if (node.kind !== 339 /* NotEmittedStatement */ - && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && sourceMapRange.end >= 0) { - emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); - } - } + function getNextPipelinePhase(currentPhase, emitHint, node) { + return getPipelinePhase(currentPhase + 1, emitHint, node); + } + function pipelineEmitWithNotification(hint, node) { + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + var savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); } - // Emit trailing comments - if (commentRange) { - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = false; - } - emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + else { + pipelineEmitWithHintWorker(hint, node); } - preserveSourceNewlines = savedPreserveSourceNewlines; onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + // clear the parenthesizer rule as we ascend + currentParenthesizerRule = undefined; } - function emitWithContext(node, emitCallback) { - var savedPreserveSourceNewlines = preserveSourceNewlines; - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; - var emitComments = shouldEmitComments(node); - var emitSourceMaps = shouldEmitSourceMaps(node); - beforeEmitWithContext(node, emitComments, emitSourceMaps); - emitCallback(node); - afterEmitWithContext(node, emitComments, emitSourceMaps, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines); - } - function emitWorker(node) { - switch (node.kind) { - // Literals - case 8 /* NumericLiteral */: - case 9 /* BigIntLiteral */: - return emitNumericOrBigIntLiteral(node); - case 10 /* StringLiteral */: - case 13 /* RegularExpressionLiteral */: - case 14 /* NoSubstitutionTemplateLiteral */: - return emitLiteral(node, /*jsxAttributeEscape*/ false); - case 11 /* JsxText */: - return emitJsxText(node); - // Pseudo-literals - case 15 /* TemplateHead */: - case 16 /* TemplateMiddle */: - case 17 /* TemplateTail */: - return emitLiteral(node, /*jsxAttributeEscape*/ false); - // Identifiers and PrivateIdentifiers - case 78 /* Identifier */: - return emitIdentifier(node); - case 79 /* PrivateIdentifier */: - return emitPrivateIdentifier(node); - // Names - case 158 /* QualifiedName */: - return emitQualifiedName(node); - case 159 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - // Signature elements - case 160 /* TypeParameter */: - return emitTypeParameter(node); - case 161 /* Parameter */: - return emitParameter(node); - case 162 /* Decorator */: - return emitDecorator(node); - // Type members - case 163 /* PropertySignature */: - return emitPropertySignature(node); - case 164 /* PropertyDeclaration */: - return emitPropertyDeclaration(node); - case 165 /* MethodSignature */: - return emitMethodSignature(node); - case 166 /* MethodDeclaration */: - return emitMethodDeclaration(node); - case 167 /* Constructor */: - return emitConstructor(node); - case 168 /* GetAccessor */: - case 169 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 170 /* CallSignature */: - return emitCallSignature(node); - case 171 /* ConstructSignature */: - return emitConstructSignature(node); - case 172 /* IndexSignature */: - return emitIndexSignature(node); - // Types - case 173 /* TypePredicate */: - return emitTypePredicate(node); - case 174 /* TypeReference */: - return emitTypeReference(node); - case 175 /* FunctionType */: - return emitFunctionType(node); - case 176 /* ConstructorType */: - return emitConstructorType(node); - case 177 /* TypeQuery */: - return emitTypeQuery(node); - case 178 /* TypeLiteral */: - return emitTypeLiteral(node); - case 179 /* ArrayType */: - return emitArrayType(node); - case 180 /* TupleType */: - return emitTupleType(node); - case 181 /* OptionalType */: - return emitOptionalType(node); - // SyntaxKind.RestType is handled below - case 183 /* UnionType */: - return emitUnionType(node); - case 184 /* IntersectionType */: - return emitIntersectionType(node); - case 185 /* ConditionalType */: - return emitConditionalType(node); - case 186 /* InferType */: - return emitInferType(node); - case 187 /* ParenthesizedType */: - return emitParenthesizedType(node); - case 188 /* ThisType */: - return emitThisType(); - case 189 /* TypeOperator */: - return emitTypeOperator(node); - case 190 /* IndexedAccessType */: - return emitIndexedAccessType(node); - case 191 /* MappedType */: - return emitMappedType(node); - case 192 /* LiteralType */: - return emitLiteralType(node); - case 193 /* NamedTupleMember */: - return emitNamedTupleMember(node); - case 194 /* TemplateLiteralType */: - return emitTemplateType(node); - case 195 /* TemplateLiteralTypeSpan */: - return emitTemplateTypeSpan(node); - case 196 /* ImportType */: - return emitImportTypeNode(node); - // Binding patterns - case 197 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 198 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 199 /* BindingElement */: - return emitBindingElement(node); - // Expressions - case 200 /* ArrayLiteralExpression */: - return emitArrayLiteralExpression(node); - case 201 /* ObjectLiteralExpression */: - return emitObjectLiteralExpression(node); - case 202 /* PropertyAccessExpression */: - return emitPropertyAccessExpression(node); - case 203 /* ElementAccessExpression */: - return emitElementAccessExpression(node); - case 204 /* CallExpression */: - return emitCallExpression(node); - case 205 /* NewExpression */: - return emitNewExpression(node); - case 206 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 207 /* TypeAssertionExpression */: - return emitTypeAssertionExpression(node); - case 208 /* ParenthesizedExpression */: - return emitParenthesizedExpression(node); - case 209 /* FunctionExpression */: - return emitFunctionExpression(node); - case 210 /* ArrowFunction */: - return emitArrowFunction(node); - case 211 /* DeleteExpression */: - return emitDeleteExpression(node); - case 212 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 213 /* VoidExpression */: - return emitVoidExpression(node); - case 214 /* AwaitExpression */: - return emitAwaitExpression(node); - case 215 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 216 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 217 /* BinaryExpression */: - return emitBinaryExpression(node); - case 218 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 219 /* TemplateExpression */: - return emitTemplateExpression(node); - case 220 /* YieldExpression */: - return emitYieldExpression(node); - case 221 /* SpreadElement */: - return emitSpreadExpression(node); - case 222 /* ClassExpression */: - return emitClassExpression(node); - case 223 /* OmittedExpression */: - return; - case 224 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(node); - case 225 /* AsExpression */: - return emitAsExpression(node); - case 226 /* NonNullExpression */: - return emitNonNullExpression(node); - case 227 /* MetaProperty */: - return emitMetaProperty(node); - case 228 /* SyntheticExpression */: - ts.Debug.fail("SyntheticExpression should never be printed."); - break; - // Misc - case 229 /* TemplateSpan */: - return emitTemplateSpan(node); - case 230 /* SemicolonClassElement */: - return emitSemicolonClassElement(); - // Element - case 231 /* Block */: - return emitBlock(node); - case 232 /* EmptyStatement */: - return emitEmptyStatement(/*isEmbeddedStatement*/ false); - case 233 /* VariableStatement */: - return emitVariableStatement(node); - case 234 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 235 /* IfStatement */: - return emitIfStatement(node); - case 236 /* DoStatement */: - return emitDoStatement(node); - case 237 /* WhileStatement */: - return emitWhileStatement(node); - case 238 /* ForStatement */: - return emitForStatement(node); - case 239 /* ForInStatement */: - return emitForInStatement(node); - case 240 /* ForOfStatement */: - return emitForOfStatement(node); - case 241 /* ContinueStatement */: - return emitContinueStatement(node); - case 242 /* BreakStatement */: - return emitBreakStatement(node); - case 243 /* ReturnStatement */: - return emitReturnStatement(node); - case 244 /* WithStatement */: - return emitWithStatement(node); - case 245 /* SwitchStatement */: - return emitSwitchStatement(node); - case 246 /* LabeledStatement */: - return emitLabeledStatement(node); - case 247 /* ThrowStatement */: - return emitThrowStatement(node); - case 248 /* TryStatement */: - return emitTryStatement(node); - case 249 /* DebuggerStatement */: - return emitDebuggerStatement(node); - // Declarations - case 250 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 251 /* VariableDeclarationList */: - return emitVariableDeclarationList(node); - case 252 /* FunctionDeclaration */: - return emitFunctionDeclaration(node); - case 253 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 254 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 255 /* TypeAliasDeclaration */: - return emitTypeAliasDeclaration(node); - case 256 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 257 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 258 /* ModuleBlock */: - return emitModuleBlock(node); - case 259 /* CaseBlock */: - return emitCaseBlock(node); - case 260 /* NamespaceExportDeclaration */: - return emitNamespaceExportDeclaration(node); - case 261 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 262 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 263 /* ImportClause */: - return emitImportClause(node); - case 264 /* NamespaceImport */: - return emitNamespaceImport(node); - case 265 /* NamedImports */: - return emitNamedImports(node); - case 266 /* ImportSpecifier */: - return emitImportSpecifier(node); - case 267 /* ExportAssignment */: - return emitExportAssignment(node); - case 268 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 269 /* NamedExports */: - return emitNamedExports(node); - case 270 /* NamespaceExport */: - return emitNamespaceExport(node); - case 271 /* ExportSpecifier */: - return emitExportSpecifier(node); - case 272 /* MissingDeclaration */: - return; - // Module references - case 273 /* ExternalModuleReference */: - return emitExternalModuleReference(node); - // JSX - case 274 /* JsxElement */: - return emitJsxElement(node); - case 275 /* JsxSelfClosingElement */: - return emitJsxSelfClosingElement(node); - case 278 /* JsxFragment */: - return emitJsxFragment(node); - case 276 /* JsxOpeningElement */: - case 279 /* JsxOpeningFragment */: - return emitJsxOpeningElementOrFragment(node); - case 277 /* JsxClosingElement */: - case 280 /* JsxClosingFragment */: - return emitJsxClosingElementOrFragment(node); - case 281 /* JsxAttribute */: - return emitJsxAttribute(node); - case 282 /* JsxAttributes */: - return emitJsxAttributes(node); - case 283 /* JsxSpreadAttribute */: - return emitJsxSpreadAttribute(node); - case 284 /* JsxExpression */: - return emitJsxExpression(node); - // Clauses - case 285 /* CaseClause */: - return emitCaseClause(node); - case 286 /* DefaultClause */: - return emitDefaultClause(node); - case 287 /* HeritageClause */: - return emitHeritageClause(node); - case 288 /* CatchClause */: - return emitCatchClause(node); - // Property assignments - case 289 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 290 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 291 /* SpreadAssignment */: - return emitSpreadAssignment(node); - // Enum - case 292 /* EnumMember */: - return emitEnumMember(node); - // Unparsed - case 293 /* UnparsedPrologue */: - return writeUnparsedNode(node); - case 300 /* UnparsedSource */: - case 294 /* UnparsedPrepend */: - return emitUnparsedSourceOrPrepend(node); - case 295 /* UnparsedText */: - case 296 /* UnparsedInternalText */: - return emitUnparsedTextLike(node); - case 297 /* UnparsedSyntheticReference */: - return emitUnparsedSyntheticReference(node); - // Top-level nodes - case 298 /* SourceFile */: - return emitSourceFile(node); - case 299 /* Bundle */: - ts.Debug.fail("Bundles should be printed using printBundle"); - break; - // SyntaxKind.UnparsedSource (handled above) - case 301 /* InputFiles */: - ts.Debug.fail("InputFiles should not be printed"); - break; - // JSDoc nodes (only used in codefixes currently) - case 302 /* JSDocTypeExpression */: - return emitJSDocTypeExpression(node); - case 303 /* JSDocNameReference */: - return emitJSDocNameReference(node); - case 304 /* JSDocAllType */: - return writePunctuation("*"); - case 305 /* JSDocUnknownType */: - return writePunctuation("?"); - case 306 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 307 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 308 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 309 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 182 /* RestType */: - case 310 /* JSDocVariadicType */: - return emitRestOrJSDocVariadicType(node); - // SyntaxKind.JSDocNamepathType (missing) - case 312 /* JSDocComment */: - return emitJSDoc(node); - case 314 /* JSDocTypeLiteral */: - return emitJSDocTypeLiteral(node); - case 315 /* JSDocSignature */: - return emitJSDocSignature(node); - case 317 /* JSDocTag */: - case 322 /* JSDocClassTag */: - return emitJSDocSimpleTag(node); - case 318 /* JSDocAugmentsTag */: - case 319 /* JSDocImplementsTag */: - return emitJSDocHeritageTag(node); - // SyntaxKind.JSDocAuthorTag (missing) - // SyntaxKind.JSDocDeprecatedTag (missing) - // SyntaxKind.JSDocClassTag (see JSDocTag, above) - // SyntaxKind.JSDocPublicTag (missing) - // SyntaxKind.JSDocPrivateTag (missing) - // SyntaxKind.JSDocProtectedTag (missing) - // SyntaxKind.JSDocReadonlyTag (missing) - case 328 /* JSDocCallbackTag */: - return emitJSDocCallbackTag(node); - // SyntaxKind.JSDocEnumTag (see below) - case 330 /* JSDocParameterTag */: - case 337 /* JSDocPropertyTag */: - return emitJSDocPropertyLikeTag(node); - case 329 /* JSDocEnumTag */: - case 331 /* JSDocReturnTag */: - case 332 /* JSDocThisTag */: - case 333 /* JSDocTypeTag */: - return emitJSDocSimpleTypedTag(node); - case 334 /* JSDocTemplateTag */: - return emitJSDocTemplateTag(node); - case 335 /* JSDocTypedefTag */: - return emitJSDocTypedefTag(node); - case 336 /* JSDocSeeTag */: - return emitJSDocSeeTag(node); - // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) - // Synthesized list - case 338 /* SyntaxList */: - ts.Debug.fail("SyntaxList should not be printed"); - break; - // Transformation nodes - case 339 /* NotEmittedStatement */: - break; - case 340 /* PartiallyEmittedExpression */: - return emitPartiallyEmittedExpression(node); - case 341 /* CommaListExpression */: - return emitCommaList(node); - case 342 /* MergeDeclarationMarker */: - case 343 /* EndOfDeclarationMarker */: - break; - case 344 /* SyntheticReferenceExpression */: - ts.Debug.fail("SyntheticReferenceExpression should not be printed"); + function pipelineEmitWithHintWorker(hint, node) { + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 6 /* JsxAttributeValue */) + return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } + if (hint === 4 /* Unspecified */) { + switch (node.kind) { + // Pseudo-literals + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return emitLiteral(node, /*jsxAttributeEscape*/ false); + // Identifiers + case 78 /* Identifier */: + return emitIdentifier(node); + // PrivateIdentifiers + case 79 /* PrivateIdentifier */: + return emitPrivateIdentifier(node); + // Parse tree nodes + // Names + case 158 /* QualifiedName */: + return emitQualifiedName(node); + case 159 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 160 /* TypeParameter */: + return emitTypeParameter(node); + case 161 /* Parameter */: + return emitParameter(node); + case 162 /* Decorator */: + return emitDecorator(node); + // Type members + case 163 /* PropertySignature */: + return emitPropertySignature(node); + case 164 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 165 /* MethodSignature */: + return emitMethodSignature(node); + case 166 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 167 /* Constructor */: + return emitConstructor(node); + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 170 /* CallSignature */: + return emitCallSignature(node); + case 171 /* ConstructSignature */: + return emitConstructSignature(node); + case 172 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 173 /* TypePredicate */: + return emitTypePredicate(node); + case 174 /* TypeReference */: + return emitTypeReference(node); + case 175 /* FunctionType */: + return emitFunctionType(node); + case 176 /* ConstructorType */: + return emitConstructorType(node); + case 177 /* TypeQuery */: + return emitTypeQuery(node); + case 178 /* TypeLiteral */: + return emitTypeLiteral(node); + case 179 /* ArrayType */: + return emitArrayType(node); + case 180 /* TupleType */: + return emitTupleType(node); + case 181 /* OptionalType */: + return emitOptionalType(node); + // SyntaxKind.RestType is handled below + case 183 /* UnionType */: + return emitUnionType(node); + case 184 /* IntersectionType */: + return emitIntersectionType(node); + case 185 /* ConditionalType */: + return emitConditionalType(node); + case 186 /* InferType */: + return emitInferType(node); + case 187 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 224 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 188 /* ThisType */: + return emitThisType(); + case 189 /* TypeOperator */: + return emitTypeOperator(node); + case 190 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 191 /* MappedType */: + return emitMappedType(node); + case 192 /* LiteralType */: + return emitLiteralType(node); + case 193 /* NamedTupleMember */: + return emitNamedTupleMember(node); + case 194 /* TemplateLiteralType */: + return emitTemplateType(node); + case 195 /* TemplateLiteralTypeSpan */: + return emitTemplateTypeSpan(node); + case 196 /* ImportType */: + return emitImportTypeNode(node); + // Binding patterns + case 197 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 198 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 199 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 229 /* TemplateSpan */: + return emitTemplateSpan(node); + case 230 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 231 /* Block */: + return emitBlock(node); + case 233 /* VariableStatement */: + return emitVariableStatement(node); + case 232 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 234 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 235 /* IfStatement */: + return emitIfStatement(node); + case 236 /* DoStatement */: + return emitDoStatement(node); + case 237 /* WhileStatement */: + return emitWhileStatement(node); + case 238 /* ForStatement */: + return emitForStatement(node); + case 239 /* ForInStatement */: + return emitForInStatement(node); + case 240 /* ForOfStatement */: + return emitForOfStatement(node); + case 241 /* ContinueStatement */: + return emitContinueStatement(node); + case 242 /* BreakStatement */: + return emitBreakStatement(node); + case 243 /* ReturnStatement */: + return emitReturnStatement(node); + case 244 /* WithStatement */: + return emitWithStatement(node); + case 245 /* SwitchStatement */: + return emitSwitchStatement(node); + case 246 /* LabeledStatement */: + return emitLabeledStatement(node); + case 247 /* ThrowStatement */: + return emitThrowStatement(node); + case 248 /* TryStatement */: + return emitTryStatement(node); + case 249 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 250 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 251 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 252 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 253 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 254 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 255 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 256 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 257 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 258 /* ModuleBlock */: + return emitModuleBlock(node); + case 259 /* CaseBlock */: + return emitCaseBlock(node); + case 260 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 261 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 262 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 263 /* ImportClause */: + return emitImportClause(node); + case 264 /* NamespaceImport */: + return emitNamespaceImport(node); + case 270 /* NamespaceExport */: + return emitNamespaceExport(node); + case 265 /* NamedImports */: + return emitNamedImports(node); + case 266 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 267 /* ExportAssignment */: + return emitExportAssignment(node); + case 268 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 269 /* NamedExports */: + return emitNamedExports(node); + case 271 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 272 /* MissingDeclaration */: + return; + // Module references + case 273 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 11 /* JsxText */: + return emitJsxText(node); + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 277 /* JsxClosingElement */: + case 280 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 281 /* JsxAttribute */: + return emitJsxAttribute(node); + case 282 /* JsxAttributes */: + return emitJsxAttributes(node); + case 283 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 284 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 285 /* CaseClause */: + return emitCaseClause(node); + case 286 /* DefaultClause */: + return emitDefaultClause(node); + case 287 /* HeritageClause */: + return emitHeritageClause(node); + case 288 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 289 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 290 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 291 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 292 /* EnumMember */: + return emitEnumMember(node); + // Unparsed + case 293 /* UnparsedPrologue */: + return writeUnparsedNode(node); + case 300 /* UnparsedSource */: + case 294 /* UnparsedPrepend */: + return emitUnparsedSourceOrPrepend(node); + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: + return emitUnparsedTextLike(node); + case 297 /* UnparsedSyntheticReference */: + return emitUnparsedSyntheticReference(node); + // Top-level nodes + case 298 /* SourceFile */: + return emitSourceFile(node); + case 299 /* Bundle */: + return ts.Debug.fail("Bundles should be printed using printBundle"); + // SyntaxKind.UnparsedSource (handled above) + case 301 /* InputFiles */: + return ts.Debug.fail("InputFiles should not be printed"); + // JSDoc nodes (only used in codefixes currently) + case 302 /* JSDocTypeExpression */: + return emitJSDocTypeExpression(node); + case 303 /* JSDocNameReference */: + return emitJSDocNameReference(node); + case 304 /* JSDocAllType */: + return writePunctuation("*"); + case 305 /* JSDocUnknownType */: + return writePunctuation("?"); + case 306 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 307 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 308 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 309 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 182 /* RestType */: + case 310 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + case 311 /* JSDocNamepathType */: + return; + case 312 /* JSDocComment */: + return emitJSDoc(node); + case 314 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 315 /* JSDocSignature */: + return emitJSDocSignature(node); + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + return emitJSDocSimpleTag(node); + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + return emitJSDocHeritageTag(node); + case 320 /* JSDocAuthorTag */: + case 321 /* JSDocDeprecatedTag */: + return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 327 /* JSDocOverrideTag */: + return; + case 328 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + // SyntaxKind.JSDocEnumTag (see below) + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 329 /* JSDocEnumTag */: + case 331 /* JSDocReturnTag */: + case 332 /* JSDocThisTag */: + case 333 /* JSDocTypeTag */: + return emitJSDocSimpleTypedTag(node); + case 334 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 335 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 336 /* JSDocSeeTag */: + return emitJSDocSeeTag(node); + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) + // Transformation nodes + case 339 /* NotEmittedStatement */: + case 343 /* EndOfDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: + return; + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + if (substituteNode !== ts.noEmitSubstitution) { + var substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } + } + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node, /*jsxAttributeEscape*/ false); + // Identifiers + case 78 /* Identifier */: + return emitIdentifier(node); + // Expressions + case 200 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 201 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 202 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 203 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 204 /* CallExpression */: + return emitCallExpression(node); + case 205 /* NewExpression */: + return emitNewExpression(node); + case 206 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 207 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 208 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 209 /* FunctionExpression */: + return emitFunctionExpression(node); + case 210 /* ArrowFunction */: + return emitArrowFunction(node); + case 211 /* DeleteExpression */: + return emitDeleteExpression(node); + case 212 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 213 /* VoidExpression */: + return emitVoidExpression(node); + case 214 /* AwaitExpression */: + return emitAwaitExpression(node); + case 215 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 216 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 217 /* BinaryExpression */: + return emitBinaryExpression(node); + case 218 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 219 /* TemplateExpression */: + return emitTemplateExpression(node); + case 220 /* YieldExpression */: + return emitYieldExpression(node); + case 221 /* SpreadElement */: + return emitSpreadElement(node); + case 222 /* ClassExpression */: + return emitClassExpression(node); + case 223 /* OmittedExpression */: + return; + case 225 /* AsExpression */: + return emitAsExpression(node); + case 226 /* NonNullExpression */: + return emitNonNullExpression(node); + case 227 /* MetaProperty */: + return emitMetaProperty(node); + case 228 /* SyntheticExpression */: + return ts.Debug.fail("SyntheticExpression should never be printed."); + // JSX + case 274 /* JsxElement */: + return emitJsxElement(node); + case 275 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 278 /* JsxFragment */: + return emitJsxFragment(node); + // Synthesized list + case 338 /* SyntaxList */: + return ts.Debug.fail("SyntaxList should not be printed"); + // Transformation nodes + case 339 /* NotEmittedStatement */: + return; + case 340 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 341 /* CommaListExpression */: + return emitCommaList(node); + case 342 /* MergeDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: + return; + case 344 /* SyntheticReferenceExpression */: + return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); + } } if (ts.isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); if (ts.isTokenKind(node.kind)) return writeTokenNode(node, writePunctuation); + ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); } function emitMappedTypeParameter(node) { emit(node.name); @@ -104160,6 +104715,13 @@ var ts; writeSpace(); emit(node.constraint); } + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node); + ts.Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); + } function getHelpersFromBundledSourceFiles(bundle) { var result; if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) { @@ -104262,9 +104824,6 @@ var ts; writeStringLiteral(text); } } - function emitStringLiteralWithJsxAttributeEscape(node) { - emitLiteral(node, /*jsxAttributeEscape*/ true); - } // SyntaxKind.UnparsedSource // SyntaxKind.UnparsedPrepend function emitUnparsedSourceOrPrepend(unparsed) { @@ -104323,7 +104882,7 @@ var ts; } function emitEntityName(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -104331,7 +104890,7 @@ var ts; } function emitComputedPropertyName(node) { writePunctuation("["); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } // @@ -104365,11 +104924,11 @@ 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); + 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); } function emitDecorator(decorator) { writePunctuation("@"); - emit(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } // // Type members @@ -104534,7 +105093,7 @@ var ts; writePunctuation("}"); } function emitArrayType(node) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -104557,21 +105116,21 @@ var ts; emit(node.type); } function emitOptionalType(node) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 516 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node) { - emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -104597,10 +105156,10 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -104623,7 +105182,7 @@ var ts; writeSpace(); } writePunctuation("["); - emitWithContext(node.typeParameter, emitMappedTypeParameter); + pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter); if (node.nameType) { writeSpace(); writeKeyword("as"); @@ -104651,7 +105210,7 @@ var ts; writePunctuation("}"); } function emitLiteralType(node) { - emit(node.literal); + emitExpression(node.literal); } function emitTemplateType(node) { emit(node.head); @@ -104693,7 +105252,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // Expressions @@ -104701,7 +105260,7 @@ var ts; function emitArrayLiteralExpression(node) { var elements = node.elements; var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; - emitList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -104717,7 +105276,7 @@ var ts; } } function emitPropertyAccessExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos); var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); var linesAfterDot = getLinesBetweenNodes(node, token, node.name); @@ -104759,41 +105318,41 @@ var ts; } } function emitElementAccessExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); - emit(node.argumentExpression); + emitExpression(node.argumentExpression); emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitList(node, node.arguments, 2576 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitList(node, node.arguments, 18960 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node) { - emit(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); - emit(node.template); + emitExpression(node.template); } function emitTypeAssertionExpression(node) { writePunctuation("<"); emit(node.type); writePunctuation(">"); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emit(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -104817,29 +105376,29 @@ var ts; function emitDeleteExpression(node) { emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node) { writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emit(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node) { // In some cases, we need to emit a space between the operator and the operand. One obvious case @@ -104860,11 +105419,11 @@ var ts; || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { - emit(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } function createEmitBinaryExpression() { - return ts.createBinaryExpressionTrampoline(onEnter, maybeEmitExpression, onOperator, maybeEmitExpression, onExit, /*foldState*/ undefined); + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); function onEnter(node, state) { if (state) { state.stackIndex++; @@ -104874,7 +105433,12 @@ var ts; state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); - beforeEmitWithContext(node, emitComments_1, emitSourceMaps); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (emitComments_1) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); } else { state = { @@ -104889,6 +105453,9 @@ var ts; } return state; } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } function onOperator(operatorToken, _state, node) { var isCommaOperator = operatorToken.kind !== 27 /* CommaToken */; var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); @@ -104899,6 +105466,9 @@ var ts; emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } function onExit(node, state) { var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); @@ -104910,16 +105480,35 @@ var ts; var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex]; var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex]; - afterEmitWithContext(node, shouldEmitComments_1, shouldEmitSourceMaps_1, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines); + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps_1) + emitSourceMapsAfterNode(node); + if (shouldEmitComments_1) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); state.stackIndex--; } } - function maybeEmitExpression(next) { - // Push a new frame for binary expressions, otherwise emit all other expressions. - if (ts.isBinaryExpression(next)) { - return next; + function maybeEmitExpression(next, parent, side) { + var parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); + var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next); + if (pipelinePhase === pipelineEmitWithSubstitution) { + ts.Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression)); + pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next); + lastSubstitution = undefined; } - emit(next); + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (ts.isBinaryExpression(next)) { + return next; + } + } + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1 /* Expression */, next); } } function emitConditionalExpression(node) { @@ -104927,16 +105516,16 @@ var ts; var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emit(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true); - emit(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true); - emit(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { @@ -104946,22 +105535,22 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node) { + function emitSpreadElement(node) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emit(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -104970,7 +105559,7 @@ var ts; } } function emitNonNullExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } function emitMetaProperty(node) { @@ -104982,7 +105571,7 @@ var ts; // Misc // function emitTemplateSpan(node) { - emit(node.expression); + emitExpression(node.expression); emit(node.literal); } // @@ -105012,11 +105601,8 @@ var ts; writeTrailingSemicolon(); } } - function emitEmbeddedEmptyStatement(_node) { - emitEmptyStatement(/*isEmbeddedStatement*/ true); - } function emitExpressionStatement(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); // Emit semicolon in non json files // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { @@ -105027,7 +105613,7 @@ var ts; var openParenPos = emitTokenWithComment(98 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { @@ -105046,7 +105632,7 @@ var ts; var openParenPos = emitTokenWithComment(114 /* WhileKeyword */, startPos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); } function emitDoStatement(node) { @@ -105085,7 +105671,7 @@ var ts; writeSpace(); emitTokenWithComment(100 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -105098,7 +105684,7 @@ var ts; writeSpace(); emitTokenWithComment(157 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -105108,7 +105694,7 @@ var ts; emit(node); } else { - emit(node); + emitExpression(node); } } } @@ -105155,7 +105741,7 @@ var ts; var openParenPos = emitTokenWithComment(115 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -105163,7 +105749,7 @@ var ts; var openParenPos = emitTokenWithComment(106 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); @@ -105205,7 +105791,7 @@ var ts; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); @@ -105221,7 +105807,7 @@ var ts; writeKeyword("function"); emit(node.asteriskToken); writeSpace(); - emit(node.name); + emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } function emitSignatureAndBody(node, emitSignatureHead) { @@ -105245,7 +105831,7 @@ var ts; else { emitSignatureHead(node); writeSpace(); - emit(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -105320,7 +105906,7 @@ var ts; increaseIndent(); } else { - emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, /*parenthesizerRule*/ undefined, statementOffset); } } function emitClassDeclaration(node) { @@ -105333,7 +105919,7 @@ var ts; writeKeyword("class"); if (node.name) { writeSpace(); - emit(node.name); + emitIdentifierName(node.name); } var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { @@ -105431,7 +106017,7 @@ var ts; } function emitModuleReference(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -105447,7 +106033,7 @@ var ts; emitTokenWithComment(153 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } - emit(node.moduleSpecifier); + emitExpression(node.moduleSpecifier); writeTrailingSemicolon(); } function emitImportClause(node) { @@ -105485,7 +106071,9 @@ var ts; emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); - emit(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(62 /* EqualsToken */) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -105506,7 +106094,7 @@ var ts; var fromPos = node.exportClause ? node.exportClause.end : nextPos; emitTokenWithComment(153 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); - emit(node.moduleSpecifier); + emitExpression(node.moduleSpecifier); } writeTrailingSemicolon(); } @@ -105553,7 +106141,7 @@ var ts; function emitExternalModuleReference(node) { writeKeyword("require"); writePunctuation("("); - emit(node.expression); + emitExpression(node.expression); writePunctuation(")"); } // @@ -105605,17 +106193,13 @@ var ts; function emitJsxAttributes(node) { emitList(node, node.properties, 262656 /* JsxElementAttributes */); } - function emitJsxAttributeValue(node) { - var emitCallback = ts.isStringLiteral(node) ? emitStringLiteralWithJsxAttributeEscape : emitWorker; - emitWithContext(node, emitCallback); - } function emitJsxAttribute(node) { emit(node.name); emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue); } function emitJsxSpreadAttribute(node) { writePunctuation("{..."); - emit(node.expression); + emitExpression(node.expression); writePunctuation("}"); } function hasTrailingCommentsAtPosition(pos) { @@ -105640,7 +106224,7 @@ var ts; } var end = emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); emit(node.dotDotDotToken); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(19 /* CloseBraceToken */, ((_a = node.expression) === null || _a === void 0 ? void 0 : _a.end) || end, writePunctuation, node); if (isMultiline) { writer.decreaseIndent(); @@ -105649,7 +106233,7 @@ var ts; } function emitJsxTagName(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -105661,7 +106245,7 @@ var ts; function emitCaseClause(node) { emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { @@ -105722,7 +106306,7 @@ var ts; var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emit(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node) { emit(node.name); @@ -105730,13 +106314,13 @@ var ts; writeSpace(); writePunctuation("="); writeSpace(); - emit(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node) { if (node.expression) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } // @@ -105744,7 +106328,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // JSDoc @@ -105989,15 +106573,15 @@ var ts; emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + emitList(node, statements, 1 /* MultiLine */, /*parenthesizerRule*/ undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } // Transformation nodes function emitPartiallyEmittedExpression(node) { - emit(node.expression); + emitExpression(node.expression); } function emitCommaList(node) { - emitList(node, node.elements, 528 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -106143,12 +106727,12 @@ var ts; emit(node); } } - function emitInitializer(node, equalCommentStartPos, container) { + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); - emit(node); + emitExpression(node, parenthesizerRule); } } function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { @@ -106163,10 +106747,10 @@ var ts; emit(node); } } - function emitExpressionWithLeadingSpace(node) { + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { if (node) { writeSpace(); - emit(node); + emitExpression(node, parenthesizerRule); } } function emitWithTrailingSpace(node) { @@ -106184,7 +106768,7 @@ var ts; writeLine(); increaseIndent(); if (ts.isEmptyStatement(node)) { - emitWithContext(node, emitEmbeddedEmptyStatement); + pipelineEmit(5 /* EmbeddedStatement */, node); } else { emit(node); @@ -106196,7 +106780,7 @@ var ts; emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures @@ -106257,7 +106841,13 @@ var ts; break; } } - function emitList(parentNode, children, format, start, count) { + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; @@ -106361,7 +106951,12 @@ var ts; shouldEmitInterveningComments = mayEmitInterveningComments; } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); shouldDecreaseIndentAfterEmit = false; @@ -107097,6 +107692,33 @@ var ts; return node; } // Comments + function pipelineEmitWithComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit leading comments + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit trailing comments + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; @@ -107392,6 +108014,50 @@ var ts; } return node.parsedSourceMap || undefined; } + function pipelineEmitWithSourceMaps(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node); + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit leading sourcemap + if (ts.isUnparsedNode(node)) { + ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); + var parsed = getParsedSourceMap(node.parent); + if (parsed && sourceMapGenerator) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); + } + } + else { + var source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 339 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + } + } + } + function emitSourceMapsAfterNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit trailing sourcemap + if (!ts.isUnparsedNode(node)) { + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = false; + } + if (node.kind !== 339 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); + } + } + } /** * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source */ @@ -107484,736 +108150,6 @@ var ts; } } ts.createPrinter = createPrinter; - var PreprintPipelinePhase; - (function (PreprintPipelinePhase) { - PreprintPipelinePhase[PreprintPipelinePhase["Notification"] = 0] = "Notification"; - PreprintPipelinePhase[PreprintPipelinePhase["Substitution"] = 1] = "Substitution"; - PreprintPipelinePhase[PreprintPipelinePhase["Visit"] = 2] = "Visit"; - })(PreprintPipelinePhase || (PreprintPipelinePhase = {})); - function createPreprinter(handlers) { - var _a = handlers.substituteNode, substituteNode = _a === void 0 ? ts.noEmitSubstitution : _a, _b = handlers.onEmitNode, onEmitNode = _b === void 0 ? ts.noEmitNotification : _b, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled; - var pipelineResult; - // Outer visitors - // - // These visitors are invoked by inner visitors to re-enter the pipeline - // for notification and substitution. - var visit = makeVisitor(pipelineVisitorForUnspecified); - var visitSourceFile = makeVisitor(pipelineVisitorForSourceFile, ts.isSourceFile); - var visitIdentifierName = makeVisitor(pipelineVisitorForIdentifierName, ts.isIdentifier); - var visitModuleName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isModuleName); - var visitPropertyName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isPropertyName); - var visitMemberName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isMemberName); - var visitBindingName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isBindingName); - var visitEntityName = makeVisitor(pipelineVisitorForIdentifierReferenceOrUnspecified, ts.isEntityName); - var visitExpression = makeVisitor(pipelineVisitorForExpression, ts.isExpression); - var visitForInitializer = makeVisitor(pipelineVisitorForForInitializer, ts.isForInitializer); - var visitTypeNode = makeVisitor(pipelineVisitorForUnspecified, ts.isTypeNode); - var visitEmbeddedStatement = makeVisitor(pipelineVisitorForEmbeddedStatement, ts.isStatement, ts.factory.liftToBlock); - var visitJsxAttributeValue = makeVisitor(pipelineVisitorForJsxAttributeValue, ts.isStringLiteralOrJsxExpression); - var visitMappedTypeParameter = makeVisitor(pipelineVisitorForMappedTypeParameter, ts.isTypeParameterDeclaration); - var visitConciseBody = makeVisitor(pipelineVisitorForConciseBody, ts.isConciseBody); - var visitFunctionBody = makeVisitor(pipelineVisitorForUnspecified, ts.isFunctionBody); - var visitList = makeListVisitor(pipelineVisitorForUnspecified); - var visitTypeNodeList = makeListVisitor(pipelineVisitorForUnspecified, ts.isTypeNode); - var visitExpressionList = makeListVisitor(pipelineVisitorForExpression, ts.isExpression); - var visitParameterList = makeListVisitor(pipelineVisitorForUnspecified, ts.isParameter); - function makeVisitor(outerVisitor, defaultTest, lift) { - function visit(node, test) { - return ts.visitNode(node, outerVisitor, test || defaultTest, lift); - } - return visit; - } - function makeListVisitor(outerVisitor, defaultTest) { - function visitList(nodes, test) { - if (test === void 0) { test = defaultTest || ts.returnTrue; } - return ts.visitNodes(nodes, outerVisitor, test); - } - return visitList; - } - // Pipeline Visitors - // - // These visitors execute our existing pipeline logic for notification and substitution, - // but adapted to our visitor pattern. In some cases, we refine the `EmitHint` we pass - // to the `onEmitNode` and `substituteNode` APIs to ensure they receive the appropriate - // context. - // - // For example, the ConciseBody of an arrow function could be an Identifier, in which - // case we would want to use `EmitHint.Expression` to ensure we treat the identifier - // as an expression during substitution. - function pipelineVisitorForSourceFile(node) { return pipelineVisitorWorker(0 /* SourceFile */, node); } - function pipelineVisitorForExpression(node) { return pipelineVisitorWorker(1 /* Expression */, node); } - function pipelineVisitorForIdentifierName(node) { return pipelineVisitorWorker(2 /* IdentifierName */, node); } - function pipelineVisitorForIdentifierNameOrUnspecified(node) { return pipelineVisitorWorker(ts.isIdentifier(node) ? 2 /* IdentifierName */ : 4 /* Unspecified */, node); } - function pipelineVisitorForIdentifierReferenceOrUnspecified(node) { return pipelineVisitorWorker(ts.isIdentifier(node) ? 1 /* Expression */ : 4 /* Unspecified */, node); } - function pipelineVisitorForForInitializer(node) { return pipelineVisitorWorker(ts.isVariableDeclarationList(node) ? 4 /* Unspecified */ : 1 /* Expression */, node); } - function pipelineVisitorForMappedTypeParameter(node) { return pipelineVisitorWorker(3 /* MappedTypeParameter */, node); } - function pipelineVisitorForEmbeddedStatement(node) { return pipelineVisitorWorker(ts.isEmptyStatement(node) ? 5 /* EmbeddedStatement */ : 4 /* Unspecified */, node); } - function pipelineVisitorForJsxAttributeValue(node) { return pipelineVisitorWorker(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); } - function pipelineVisitorForConciseBody(node) { return pipelineVisitorWorker(ts.isBlock(node) ? 4 /* Unspecified */ : 1 /* Expression */, node); } - function pipelineVisitorForUnspecified(node) { return pipelineVisitorWorker(4 /* Unspecified */, node); } - /** - * Adapts the emit pipeline API to work with the visitor API - */ - function pipelineVisitorWorker(hint, node) { - resetPipelineResult(); - // Get the first supported pipeline phase for this node and evaluate it. We can skip several stack - // frames if we aren't doing emit notification, so we check for substitution and direct callbacks - // and execute those immediately. - var pipelinePhase = getPipelinePhase(0 /* Notification */, node); - if (pipelinePhase === pipelineVisitDirect) { - return visitor(hint, node); - } - if (pipelinePhase === pipelineVisitWithSubstitution) { - // The next phase after substitution is always direct visitation, so we can reduce the call stack - // depth by calling the visitor directly. - return visitor(hint, substituteNode(hint, node)); - } - pipelinePhase(hint, node); - ts.Debug.assertIsDefined(pipelineResult); - var result = pipelineResult; - resetPipelineResult(); - return result; - } - function resetPipelineResult() { - pipelineResult = undefined; - } - /** - * Gets the pipeline callback to pass to the relevant API (i.e., `substituteNode` or `onEmitNode`) - */ - function getPipelinePhase(phase, node) { - switch (phase) { - case 0 /* Notification */: - if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { - return pipelineVisitWithNotification; - } - // falls through - case 1 /* Substitution */: - if (substituteNode !== ts.noEmitSubstitution) { - return pipelineVisitWithSubstitution; - } - // falls through - default: - return pipelineVisitDirect; - } - } - /** - * A callback that can be evaluated to trigger emit notification as part of the emit pipeline. - */ - function pipelineVisitWithNotification(hint, node) { - onEmitNode(hint, node, getPipelinePhase(1 /* Substitution */, node)); - } - /** - * A callback that can be evaluated to trigger JIT substitution as part of the emit pipeline. - */ - function pipelineVisitWithSubstitution(hint, node) { - // Next phase is always direct visitation, so we can reduce the call stack - // depth by calling the visitor directly. - pipelineResult = visitor(hint, substituteNode(hint, node)); - } - /** - * A callback that can be evaluated to visit the subtree of a node. - */ - function pipelineVisitDirect(hint, node) { - pipelineResult = visitor(hint, node); - } - /** - * Re-enters the visitor pattern from the pipeline pattern to perform - * tree updates and trigger parenthesization rules. - */ - function visitor(hint, node) { - // This should align with the assertions in `pipelineEmitWithHint`. - if (hint === 0 /* SourceFile */) - return preprintSourceFile(ts.cast(node, ts.isSourceFile)); - if (hint === 2 /* IdentifierName */) - return preprintIdentifier(ts.cast(node, ts.isIdentifier)); - if (hint === 6 /* JsxAttributeValue */) - return ts.cast(node, ts.isStringLiteral); - if (hint === 3 /* MappedTypeParameter */) - return preprintTypeParameterDeclaration(ts.cast(node, ts.isTypeParameterDeclaration)); - if (hint === 5 /* EmbeddedStatement */) - return ts.cast(node, ts.isEmptyStatement); - var kind = node.kind; - // No need to visit nodes without children. - if ((kind > 0 /* FirstToken */ && kind <= 157 /* LastToken */) || kind === 188 /* ThisType */) { - return node; - } - if (hint === 4 /* Unspecified */) { - if (ts.isKeyword(node.kind)) - return node; - switch (node.kind) { - // Identifiers - case 78 /* Identifier */: - return preprintIdentifier(node); - // Names - case 158 /* QualifiedName */: - ts.Debug.type(node); - return ts.factory.updateQualifiedName(node, visitEntityName(node.left), visitIdentifierName(node.right)); - case 159 /* ComputedPropertyName */: - ts.Debug.type(node); - return ts.factory.updateComputedPropertyName(node, visitExpression(node.expression)); - // Signature elements - case 160 /* TypeParameter */: - return preprintTypeParameterDeclaration(node); - case 161 /* Parameter */: - ts.Debug.type(node); - return ts.factory.updateParameterDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.dotDotDotToken, ts.isDotDotDotToken), visitBindingName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 162 /* Decorator */: - ts.Debug.type(node); - return ts.factory.updateDecorator(node, visitExpression(node.expression)); - // Type members - case 163 /* PropertySignature */: - ts.Debug.type(node); - return ts.factory.updatePropertySignature(node, visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type)); - case 164 /* PropertyDeclaration */: - ts.Debug.type(node); - return ts.factory.updatePropertyDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken || node.exclamationToken, ts.isQuestionOrExclamationToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 165 /* MethodSignature */: - ts.Debug.type(node); - return ts.factory.updateMethodSignature(node, visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 166 /* MethodDeclaration */: - ts.Debug.type(node); - return ts.factory.updateMethodDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 167 /* Constructor */: - ts.Debug.type(node); - return ts.factory.updateConstructorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitParameterList(node.parameters), visitFunctionBody(node.body)); - case 168 /* GetAccessor */: - ts.Debug.type(node); - return ts.factory.updateGetAccessorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 169 /* SetAccessor */: - ts.Debug.type(node); - return ts.factory.updateSetAccessorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visitParameterList(node.parameters), visitFunctionBody(node.body)); - case 170 /* CallSignature */: - ts.Debug.type(node); - return ts.factory.updateCallSignature(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 171 /* ConstructSignature */: - ts.Debug.type(node); - return ts.factory.updateConstructSignature(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 172 /* IndexSignature */: - ts.Debug.type(node); - return ts.factory.updateIndexSignature(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitParameterList(node.parameters), visitTypeNode(node.type)); - // Types - case 173 /* TypePredicate */: - ts.Debug.type(node); - return ts.factory.updateTypePredicateNode(node, visit(node.assertsModifier, ts.isAssertsKeyword), visit(node.parameterName, ts.isIdentifierOrThisTypeNode), visitTypeNode(node.type)); - case 174 /* TypeReference */: - ts.Debug.type(node); - return ts.factory.updateTypeReferenceNode(node, visitEntityName(node.typeName), visitTypeNodeList(node.typeArguments)); - case 175 /* FunctionType */: - ts.Debug.type(node); - return ts.factory.updateFunctionTypeNode(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), ts.visitNodes(node.parameters, pipelineVisitorForUnspecified, ts.isParameterDeclaration), visitTypeNode(node.type)); - case 176 /* ConstructorType */: - ts.Debug.type(node); - return ts.factory.updateConstructorTypeNode(node, ts.visitNodes(node.modifiers, pipelineVisitorForUnspecified, ts.isModifier), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 177 /* TypeQuery */: - ts.Debug.type(node); - return ts.factory.updateTypeQueryNode(node, visitEntityName(node.exprName)); - case 178 /* TypeLiteral */: - ts.Debug.type(node); - return ts.factory.updateTypeLiteralNode(node, visitList(node.members, ts.isTypeElement)); - case 179 /* ArrayType */: - ts.Debug.type(node); - return ts.factory.updateArrayTypeNode(node, visitTypeNode(node.elementType)); - case 180 /* TupleType */: - ts.Debug.type(node); - return ts.factory.updateTupleTypeNode(node, visitTypeNodeList(node.elements)); - case 181 /* OptionalType */: - ts.Debug.type(node); - return ts.factory.updateOptionalTypeNode(node, visitTypeNode(node.type)); - case 182 /* RestType */: - ts.Debug.type(node); - return ts.factory.updateRestTypeNode(node, visitTypeNode(node.type)); - case 183 /* UnionType */: - ts.Debug.type(node); - return ts.factory.updateUnionTypeNode(node, visitTypeNodeList(node.types)); - case 184 /* IntersectionType */: - ts.Debug.type(node); - return ts.factory.updateIntersectionTypeNode(node, visitTypeNodeList(node.types)); - case 185 /* ConditionalType */: - ts.Debug.type(node); - return ts.factory.updateConditionalTypeNode(node, visitTypeNode(node.checkType), visitTypeNode(node.extendsType), visitTypeNode(node.trueType), visitTypeNode(node.falseType)); - case 186 /* InferType */: - ts.Debug.type(node); - return ts.factory.updateInferTypeNode(node, visit(node.typeParameter, ts.isTypeParameterDeclaration)); - case 196 /* ImportType */: - ts.Debug.type(node); - return ts.factory.updateImportTypeNode(node, visitTypeNode(node.argument), visitEntityName(node.qualifier), visitTypeNodeList(node.typeArguments), node.isTypeOf); - case 193 /* NamedTupleMember */: - ts.Debug.type(node); - return ts.factory.updateNamedTupleMember(node, visit(node.dotDotDotToken, ts.isDotDotDotToken), visitIdentifierName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type)); - case 187 /* ParenthesizedType */: - ts.Debug.type(node); - return ts.factory.updateParenthesizedType(node, visitTypeNode(node.type)); - case 224 /* ExpressionWithTypeArguments */: - ts.Debug.type(node); - return ts.factory.updateExpressionWithTypeArguments(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments)); - case 189 /* TypeOperator */: - ts.Debug.type(node); - return ts.factory.updateTypeOperatorNode(node, visitTypeNode(node.type)); - case 190 /* IndexedAccessType */: - ts.Debug.type(node); - return ts.factory.updateIndexedAccessTypeNode(node, visitTypeNode(node.objectType), visitTypeNode(node.indexType)); - case 191 /* MappedType */: - ts.Debug.type(node); - return ts.factory.updateMappedTypeNode(node, visit(node.readonlyToken, ts.isReadonlyKeywordOrPlusOrMinusToken), visitMappedTypeParameter(node.typeParameter), visitTypeNode(node.nameType), visit(node.questionToken, ts.isQuestionOrPlusOrMinusToken), visitTypeNode(node.type)); - case 192 /* LiteralType */: - ts.Debug.type(node); - return ts.factory.updateLiteralTypeNode(node, visitExpression(node.literal, ts.isLiteralTypeLikeExpression)); - case 194 /* TemplateLiteralType */: - ts.Debug.type(node); - return ts.factory.updateTemplateLiteralType(node, visit(node.head, ts.isTemplateHead), visitList(node.templateSpans, ts.isTemplateLiteralTypeSpan)); - case 195 /* TemplateLiteralTypeSpan */: - ts.Debug.type(node); - return ts.factory.updateTemplateLiteralTypeSpan(node, visitTypeNode(node.type), visit(node.literal, ts.isTemplateMiddleOrTemplateTail)); - // Binding patterns - case 197 /* ObjectBindingPattern */: - ts.Debug.type(node); - return ts.factory.updateObjectBindingPattern(node, visitList(node.elements, ts.isBindingElement)); - case 198 /* ArrayBindingPattern */: - ts.Debug.type(node); - return ts.factory.updateArrayBindingPattern(node, visitList(node.elements, ts.isArrayBindingElement)); - case 199 /* BindingElement */: - ts.Debug.type(node); - return ts.factory.updateBindingElement(node, visit(node.dotDotDotToken, ts.isDotDotDotToken), visitPropertyName(node.propertyName), visitBindingName(node.name), visitExpression(node.initializer)); - // Misc - case 229 /* TemplateSpan */: - ts.Debug.type(node); - return ts.factory.updateTemplateSpan(node, visitExpression(node.expression), visit(node.literal, ts.isTemplateMiddleOrTemplateTail)); - // Element - case 231 /* Block */: - ts.Debug.type(node); - return ts.factory.updateBlock(node, visitList(node.statements, ts.isStatement)); - case 233 /* VariableStatement */: - ts.Debug.type(node); - return ts.factory.updateVariableStatement(node, visitList(node.modifiers, ts.isModifier), visit(node.declarationList, ts.isVariableDeclarationList)); - case 234 /* ExpressionStatement */: - ts.Debug.type(node); - return ts.factory.updateExpressionStatement(node, visitExpression(node.expression)); - case 235 /* IfStatement */: - ts.Debug.type(node); - return ts.factory.updateIfStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.thenStatement), visitEmbeddedStatement(node.elseStatement)); - case 236 /* DoStatement */: - ts.Debug.type(node); - return ts.factory.updateDoStatement(node, visitEmbeddedStatement(node.statement), visitExpression(node.expression)); - case 237 /* WhileStatement */: - ts.Debug.type(node); - return ts.factory.updateWhileStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 238 /* ForStatement */: - ts.Debug.type(node); - return ts.factory.updateForStatement(node, visitForInitializer(node.initializer), visitExpression(node.condition), visitExpression(node.incrementor), visitEmbeddedStatement(node.statement)); - case 239 /* ForInStatement */: - ts.Debug.type(node); - return ts.factory.updateForInStatement(node, visitForInitializer(node.initializer), visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 240 /* ForOfStatement */: - ts.Debug.type(node); - return ts.factory.updateForOfStatement(node, visit(node.awaitModifier, ts.isAwaitKeyword), visitForInitializer(node.initializer), visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 241 /* ContinueStatement */: - ts.Debug.type(node); - return ts.factory.updateContinueStatement(node, visitIdentifierName(node.label)); - case 242 /* BreakStatement */: - ts.Debug.type(node); - return ts.factory.updateBreakStatement(node, visitIdentifierName(node.label)); - case 243 /* ReturnStatement */: - ts.Debug.type(node); - return ts.factory.updateReturnStatement(node, visitExpression(node.expression)); - case 244 /* WithStatement */: - ts.Debug.type(node); - return ts.factory.updateWithStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 245 /* SwitchStatement */: - ts.Debug.type(node); - return ts.factory.updateSwitchStatement(node, visitExpression(node.expression), visit(node.caseBlock, ts.isCaseBlock)); - case 246 /* LabeledStatement */: - ts.Debug.type(node); - return ts.factory.updateLabeledStatement(node, visitIdentifierName(node.label), visitEmbeddedStatement(node.statement)); - case 247 /* ThrowStatement */: - ts.Debug.type(node); - return ts.factory.updateThrowStatement(node, visitExpression(node.expression)); - case 248 /* TryStatement */: - ts.Debug.type(node); - return ts.factory.updateTryStatement(node, visit(node.tryBlock, ts.isBlock), visit(node.catchClause, ts.isCatchClause), visit(node.finallyBlock, ts.isBlock)); - // Declarations - case 250 /* VariableDeclaration */: - ts.Debug.type(node); - return ts.factory.updateVariableDeclaration(node, visitBindingName(node.name), visit(node.exclamationToken, ts.isExclamationToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 251 /* VariableDeclarationList */: - ts.Debug.type(node); - return ts.factory.updateVariableDeclarationList(node, visitList(node.declarations, ts.isVariableDeclaration)); - case 252 /* FunctionDeclaration */: - ts.Debug.type(node); - return ts.factory.updateFunctionDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 253 /* ClassDeclaration */: - ts.Debug.type(node); - return ts.factory.updateClassDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isClassElement)); - case 254 /* InterfaceDeclaration */: - ts.Debug.type(node); - return ts.factory.updateInterfaceDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isTypeElement)); - case 255 /* TypeAliasDeclaration */: - ts.Debug.type(node); - return ts.factory.updateTypeAliasDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitTypeNode(node.type)); - case 256 /* EnumDeclaration */: - ts.Debug.type(node); - return ts.factory.updateEnumDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.members, ts.isEnumMember)); - case 257 /* ModuleDeclaration */: - ts.Debug.type(node); - return ts.factory.updateModuleDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitModuleName(node.name), visit(node.body, ts.isModuleBody)); - case 258 /* ModuleBlock */: - ts.Debug.type(node); - return ts.factory.updateModuleBlock(node, visitList(node.statements, ts.isStatement)); - case 259 /* CaseBlock */: - ts.Debug.type(node); - return ts.factory.updateCaseBlock(node, visitList(node.clauses, ts.isCaseOrDefaultClause)); - case 260 /* NamespaceExportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateNamespaceExportDeclaration(node, visitIdentifierName(node.name)); - case 261 /* ImportEqualsDeclaration */: - ts.Debug.type(node); - return ts.factory.updateImportEqualsDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), node.isTypeOnly, visitIdentifierName(node.name), visit(node.moduleReference, ts.isModuleReference)); - case 262 /* ImportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateImportDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.importClause, ts.isImportClause), visitExpression(node.moduleSpecifier)); - case 263 /* ImportClause */: - ts.Debug.type(node); - return ts.factory.updateImportClause(node, node.isTypeOnly, visitIdentifierName(node.name), visit(node.namedBindings, ts.isNamedImportBindings)); - case 264 /* NamespaceImport */: - ts.Debug.type(node); - return ts.factory.updateNamespaceImport(node, visitIdentifierName(node.name)); - case 270 /* NamespaceExport */: - ts.Debug.type(node); - return ts.factory.updateNamespaceExport(node, visitIdentifierName(node.name)); - case 265 /* NamedImports */: - ts.Debug.type(node); - return ts.factory.updateNamedImports(node, visitList(node.elements, ts.isImportSpecifier)); - case 266 /* ImportSpecifier */: - ts.Debug.type(node); - return ts.factory.updateImportSpecifier(node, visitIdentifierName(node.propertyName), visitIdentifierName(node.name)); - case 267 /* ExportAssignment */: - ts.Debug.type(node); - return ts.factory.updateExportAssignment(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitExpression(node.expression)); - case 268 /* ExportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateExportDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), node.isTypeOnly, visit(node.exportClause, ts.isNamedExportBindings), visitExpression(node.moduleSpecifier)); - case 269 /* NamedExports */: - ts.Debug.type(node); - return ts.factory.updateNamedExports(node, visitList(node.elements, ts.isExportSpecifier)); - case 271 /* ExportSpecifier */: - ts.Debug.type(node); - return ts.factory.updateExportSpecifier(node, visitIdentifierName(node.propertyName), visitIdentifierName(node.name)); - case 272 /* MissingDeclaration */: - return node; - // Module references - case 273 /* ExternalModuleReference */: - ts.Debug.type(node); - return ts.factory.updateExternalModuleReference(node, visitExpression(node.expression)); - // JSX (non-expression) - case 276 /* JsxOpeningElement */: - ts.Debug.type(node); - return ts.factory.updateJsxOpeningElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression), visitList(node.typeArguments, ts.isTypeNode), visit(node.attributes, ts.isJsxAttributes)); - case 277 /* JsxClosingElement */: - ts.Debug.type(node); - return ts.factory.updateJsxClosingElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression)); - case 281 /* JsxAttribute */: - ts.Debug.type(node); - return ts.factory.updateJsxAttribute(node, visitIdentifierName(node.name), visitJsxAttributeValue(node.initializer)); - case 282 /* JsxAttributes */: - ts.Debug.type(node); - return ts.factory.updateJsxAttributes(node, visitList(node.properties, ts.isJsxAttributeLike)); - case 283 /* JsxSpreadAttribute */: - ts.Debug.type(node); - return ts.factory.updateJsxSpreadAttribute(node, visitExpression(node.expression)); - case 284 /* JsxExpression */: - ts.Debug.type(node); - return ts.factory.updateJsxExpression(node, visitExpression(node.expression)); - // Clauses - case 285 /* CaseClause */: - ts.Debug.type(node); - return ts.factory.updateCaseClause(node, visitExpression(node.expression), visitList(node.statements, ts.isStatement)); - case 286 /* DefaultClause */: - ts.Debug.type(node); - return ts.factory.updateDefaultClause(node, visitList(node.statements, ts.isStatement)); - case 287 /* HeritageClause */: - ts.Debug.type(node); - return ts.factory.updateHeritageClause(node, visitList(node.types, ts.isExpressionWithTypeArguments)); - case 288 /* CatchClause */: - ts.Debug.type(node); - return ts.factory.updateCatchClause(node, visit(node.variableDeclaration, ts.isVariableDeclaration), visit(node.block, ts.isBlock)); - // Property assignments - case 289 /* PropertyAssignment */: - ts.Debug.type(node); - return ts.factory.updatePropertyAssignment(node, visitPropertyName(node.name), visitExpression(node.initializer)); - case 290 /* ShorthandPropertyAssignment */: - ts.Debug.type(node); - return ts.factory.updateShorthandPropertyAssignment(node, visitIdentifierName(node.name, ts.isIdentifier), visitExpression(node.objectAssignmentInitializer)); - case 291 /* SpreadAssignment */: - ts.Debug.type(node); - return ts.factory.updateSpreadAssignment(node, visitExpression(node.expression)); - // Enum - case 292 /* EnumMember */: - ts.Debug.type(node); - return ts.factory.updateEnumMember(node, visitPropertyName(node.name), visitExpression(node.initializer)); - // JSDoc nodes (only used in codefixes currently) - case 302 /* JSDocTypeExpression */: - case 303 /* JSDocNameReference */: - case 304 /* JSDocAllType */: - case 305 /* JSDocUnknownType */: - case 306 /* JSDocNullableType */: - case 307 /* JSDocNonNullableType */: - case 308 /* JSDocOptionalType */: - case 309 /* JSDocFunctionType */: - case 310 /* JSDocVariadicType */: - case 311 /* JSDocNamepathType */: - case 312 /* JSDocComment */: - case 314 /* JSDocTypeLiteral */: - case 315 /* JSDocSignature */: - case 317 /* JSDocTag */: - case 318 /* JSDocAugmentsTag */: - case 319 /* JSDocImplementsTag */: - case 320 /* JSDocAuthorTag */: - case 321 /* JSDocDeprecatedTag */: - case 322 /* JSDocClassTag */: - case 323 /* JSDocPublicTag */: - case 324 /* JSDocPrivateTag */: - case 325 /* JSDocProtectedTag */: - case 326 /* JSDocReadonlyTag */: - case 328 /* JSDocCallbackTag */: - case 329 /* JSDocEnumTag */: - case 330 /* JSDocParameterTag */: - case 337 /* JSDocPropertyTag */: - case 331 /* JSDocReturnTag */: - case 332 /* JSDocThisTag */: - case 333 /* JSDocTypeTag */: - case 334 /* JSDocTemplateTag */: - case 335 /* JSDocTypedefTag */: - case 336 /* JSDocSeeTag */: - return node; - // Transformation nodes (ignored) - } - if (ts.isExpression(node)) { - // If this was an expression that was originally in an `Unspecified` hint, - // re-trigger substitution using the correct hint. - hint = 1 /* Expression */; - if (substituteNode !== ts.noEmitSubstitution) { - node = substituteNode(hint, node); - } - } - else if (ts.isSourceFile(node)) { - return preprintSourceFile(node); - } - } - if (hint === 1 /* Expression */) { - switch (node.kind) { - // Identifiers - case 78 /* Identifier */: - return preprintIdentifier(node); - // Expression - case 200 /* ArrayLiteralExpression */: - ts.Debug.type(node); - return ts.factory.updateArrayLiteralExpression(node, visitExpressionList(node.elements)); - case 201 /* ObjectLiteralExpression */: - ts.Debug.type(node); - return ts.factory.updateObjectLiteralExpression(node, visitList(node.properties, ts.isObjectLiteralElementLike)); - case 202 /* PropertyAccessExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updatePropertyAccessChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitMemberName(node.name)); - } - ts.Debug.type(node); - return ts.factory.updatePropertyAccessExpression(node, visitExpression(node.expression), visitMemberName(node.name)); - case 203 /* ElementAccessExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateElementAccessChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitExpression(node.argumentExpression)); - } - ts.Debug.type(node); - return ts.factory.updateElementAccessExpression(node, visitExpression(node.expression), visitExpression(node.argumentExpression)); - case 204 /* CallExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateCallChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - } - ts.Debug.type(node); - return ts.factory.updateCallExpression(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - case 205 /* NewExpression */: - ts.Debug.type(node); - return ts.factory.updateNewExpression(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - case 206 /* TaggedTemplateExpression */: - ts.Debug.type(node); - return ts.factory.updateTaggedTemplateExpression(node, visitExpression(node.tag), visitTypeNodeList(node.typeArguments), visitExpression(node.template, ts.isTemplateLiteral)); - case 207 /* TypeAssertionExpression */: - ts.Debug.type(node); - return ts.factory.updateTypeAssertion(node, visitTypeNode(node.type), visitExpression(node.expression)); - case 208 /* ParenthesizedExpression */: - ts.Debug.type(node); - return ts.factory.updateParenthesizedExpression(node, visitExpression(node.expression)); - case 209 /* FunctionExpression */: - ts.Debug.type(node); - return ts.factory.updateFunctionExpression(node, visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 210 /* ArrowFunction */: - ts.Debug.type(node); - return ts.factory.updateArrowFunction(node, visitList(node.modifiers, ts.isModifier), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visit(node.equalsGreaterThanToken, ts.isEqualsGreaterThanToken), visitConciseBody(node.body)); - case 211 /* DeleteExpression */: - ts.Debug.type(node); - return ts.factory.updateDeleteExpression(node, visitExpression(node.expression)); - case 212 /* TypeOfExpression */: - ts.Debug.type(node); - return ts.factory.updateTypeOfExpression(node, visitExpression(node.expression)); - case 213 /* VoidExpression */: - ts.Debug.type(node); - return ts.factory.updateVoidExpression(node, visitExpression(node.expression)); - case 214 /* AwaitExpression */: - ts.Debug.type(node); - return ts.factory.updateAwaitExpression(node, visitExpression(node.expression)); - case 215 /* PrefixUnaryExpression */: - ts.Debug.type(node); - return ts.factory.updatePrefixUnaryExpression(node, visitExpression(node.operand)); - case 216 /* PostfixUnaryExpression */: - ts.Debug.type(node); - return ts.factory.updatePostfixUnaryExpression(node, visitExpression(node.operand)); - case 217 /* BinaryExpression */: - return preprintBinaryExpression(node); - case 218 /* ConditionalExpression */: - ts.Debug.type(node); - return ts.factory.updateConditionalExpression(node, visitExpression(node.condition), visit(node.questionToken, ts.isQuestionToken), visitExpression(node.whenTrue), visit(node.colonToken, ts.isColonToken), visitExpression(node.whenFalse)); - case 219 /* TemplateExpression */: - ts.Debug.type(node); - return ts.factory.updateTemplateExpression(node, visit(node.head, ts.isTemplateHead), visitList(node.templateSpans, ts.isTemplateSpan)); - case 220 /* YieldExpression */: - ts.Debug.type(node); - return ts.factory.updateYieldExpression(node, visit(node.asteriskToken, ts.isAsteriskToken), visitExpression(node.expression)); - case 221 /* SpreadElement */: - ts.Debug.type(node); - return ts.factory.updateSpreadElement(node, visitExpression(node.expression)); - case 222 /* ClassExpression */: - ts.Debug.type(node); - return ts.factory.updateClassExpression(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isClassElement)); - case 225 /* AsExpression */: - ts.Debug.type(node); - return ts.factory.updateAsExpression(node, visitExpression(node.expression), visitTypeNode(node.type)); - case 226 /* NonNullExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateNonNullChain(node, visitExpression(node.expression)); - } - ts.Debug.type(node); - return ts.factory.updateNonNullExpression(node, visitExpression(node.expression)); - case 227 /* MetaProperty */: - ts.Debug.type(node); - return ts.factory.updateMetaProperty(node, visitIdentifierName(node.name)); - // JSX (expression only) - case 274 /* JsxElement */: - ts.Debug.type(node); - return ts.factory.updateJsxElement(node, visit(node.openingElement, ts.isJsxOpeningElement), visitList(node.children, ts.isJsxChild), visit(node.closingElement, ts.isJsxClosingElement)); - case 275 /* JsxSelfClosingElement */: - ts.Debug.type(node); - return ts.factory.updateJsxSelfClosingElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression), visitList(node.typeArguments, ts.isTypeNode), visit(node.attributes, ts.isJsxAttributes)); - case 278 /* JsxFragment */: - ts.Debug.type(node); - return ts.factory.updateJsxFragment(node, visit(node.openingFragment, ts.isJsxOpeningFragment), visitList(node.children, ts.isJsxChild), visit(node.closingFragment, ts.isJsxClosingFragment)); - // Transformation nodes - case 340 /* PartiallyEmittedExpression */: - ts.Debug.type(node); - return ts.factory.updatePartiallyEmittedExpression(node, visitExpression(node.expression)); - case 341 /* CommaListExpression */: - ts.Debug.type(node); - return ts.factory.updateCommaListExpression(node, visitExpressionList(node.elements, ts.isExpression)); - } - } - if (ts.Debug.shouldAssert(1 /* Normal */)) { - // Any other node should not have children or this list isn't up to date. - ts.Debug.assertMissingNode(ts.forEachChild(node, ts.identity), "Expected " + ts.Debug.formatSyntaxKind(node.kind) + " to contain no children."); - } - // No need to visit nodes with no children. - return node; - } - function preprintSourceFile(node) { - return ts.factory.updateSourceFile(node, visitList(node.statements, ts.isStatement)); - } - function preprintIdentifier(node) { - return ts.factory.updateIdentifier(node, visitList(node.typeArguments, ts.isTypeNodeOrTypeParameterDeclaration)); - } - function preprintTypeParameterDeclaration(node) { - return ts.factory.updateTypeParameterDeclaration(node, visitIdentifierName(node.name), visitTypeNode(node.constraint), visitTypeNode(node.default)); - } - function createPreprintBinaryExpression() { - return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); - function onEnter(node, state) { - if (state) { - state.stackIndex++; - state.leftStack[state.stackIndex] = node.left; - state.operatorStack[state.stackIndex] = node.operatorToken; - state.rightStack[state.stackIndex] = node.right; - } - else { - state = { - stackIndex: 0, - leftStack: [node.left], - operatorStack: [node.operatorToken], - rightStack: [node.right], - }; - } - return state; - } - function onLeft(left, state, _node) { - return maybeVisitExpression(left, state, "left"); - } - function onOperator(operator, state, _node) { - state.operatorStack[state.stackIndex] = visit(operator, ts.isBinaryOperatorToken); - } - function onRight(right, state, _node) { - return maybeVisitExpression(right, state, "right"); - } - function onExit(node, state) { - var left = state.leftStack[state.stackIndex]; - var operator = state.operatorStack[state.stackIndex]; - var right = state.rightStack[state.stackIndex]; - if (state.stackIndex > 0) { - state.stackIndex--; - } - return ts.factory.updateBinaryExpression(node, left, operator, right); - } - function foldState(state, result, side) { - (side === "left" ? state.leftStack : state.rightStack)[state.stackIndex] = result; - return state; - } - function maybeVisitExpression(node, state, side) { - // Get the first supported pipeline phase for this node. We can skip several stack - // frames if we aren't doing emit notification, so we check for substitution and - // direct callbacks and execute those immediately. - var pipelinePhase = getPipelinePhase(0 /* Notification */, node); - if (pipelinePhase === pipelineVisitWithSubstitution) { - // The next phase after substitution is always direct visitation, so we can reduce the call stack - // depth by proceding to the direct visitor. - node = ts.cast(substituteNode(1 /* Expression */, node), ts.isExpression); - pipelinePhase = pipelineVisitDirect; - } - if (pipelinePhase === pipelineVisitDirect && ts.isBinaryExpression(node)) { - // If we are visiting directly and the next node is a BinaryExpression, we can - // add it to the stack and continue the trampoline. - return node; - } - else { - // Visit the expression and store the result on whichever side we are currently visiting. - (side === "left" ? state.leftStack : state.rightStack)[state.stackIndex] = visitExpression(node, ts.isExpression); - } - } - } - var preprintBinaryExpression = createPreprintBinaryExpression(); - function preprint(hint, node) { - // If we're not performing substitution or notification, we have no work to do here. - if (substituteNode === ts.noEmitSubstitution && - onEmitNode === ts.noEmitNotification) { - return node; - } - switch (hint) { - case 0 /* SourceFile */: return visitSourceFile(ts.cast(node, ts.isSourceFile)); - case 1 /* Expression */: return visitExpression(ts.cast(node, ts.isExpression)); - case 2 /* IdentifierName */: return visitIdentifierName(ts.cast(node, ts.isIdentifier)); - case 3 /* MappedTypeParameter */: return visitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 5 /* EmbeddedStatement */: return visitEmbeddedStatement(ts.cast(node, ts.isStatement)); - case 6 /* JsxAttributeValue */: return visitJsxAttributeValue(ts.cast(node, ts.isStringLiteralOrJsxExpression)); - default: return visit(node); - } - } - return preprint; - } function createBracketsMap() { var brackets = []; brackets[1024 /* Braces */] = ["{", "}"]; @@ -109434,6 +109370,7 @@ var ts; var hasEmitBlockingDiagnostics = new ts.Map(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; + var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { @@ -109448,7 +109385,7 @@ var ts; }); }; } else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } @@ -109457,7 +109394,8 @@ var ts; actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { - var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; // TODO: GH#18217 actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -109614,6 +109552,7 @@ var ts; } }); } + typeReferenceDirectiveResolutionCache = undefined; // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; var program = { @@ -109807,13 +109746,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_15 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_14.push(resolvedModule); + result_15.push(resolvedModule); } - return result_14; + return result_15; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -111245,12 +111184,14 @@ var ts; return host.getCanonicalFileName(fileName); } function processImportedModules(file) { + var _a; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var resolutions = resolveModuleNamesReusingOldState(moduleNames, file); ts.Debug.assert(resolutions.length === moduleNames.length); + var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options; for (var index = 0; index < moduleNames.length; index++) { var resolution = resolutions[index]; ts.setResolvedModule(file, moduleNames[index], resolution); @@ -111273,11 +111214,11 @@ var ts; // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !ts.getAllowJSCompilerOption(options)) + && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile)) && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -112365,7 +112306,7 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos: fileInfos, @@ -113165,7 +113106,16 @@ var ts; var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - return signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; + var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); var referencedMap; if (state.referencedMap) { @@ -113214,7 +113164,7 @@ var ts; return { fileNames: fileNames, fileInfos: fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, @@ -113246,17 +113196,16 @@ var ts; return fileIdListId; } } - function convertToReusableCompilerOptions(options, relativeToBuildInfo) { - var result = {}; + function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { + var result; var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo); + 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.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { @@ -113572,6 +113521,14 @@ var ts; state.affectedFilesPendingEmitIndex = 0; } } + function toBuilderStateFileInfo(fileInfo) { + return ts.isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + ts.isString(fileInfo.signature) ? + fileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; + } + ts.toBuilderStateFileInfo = toBuilderStateFileInfo; function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { var _a; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); @@ -113579,10 +113536,10 @@ var ts; 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), fileInfo); }); + program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); var state = { fileInfos: fileInfos, - compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, referencedMap: toMapOfReferencedSet(program.referencedMap), exportedModulesMap: toMapOfReferencedSet(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]; }), @@ -113742,9 +113699,9 @@ var ts; var resolutionsWithFailedLookups = []; var resolvedFileToResolution = ts.createMultiMap(); var hasChangedAutomaticTypeDirectiveNames = false; - var failedLookupChecks = []; - var startsWithPathChecks = []; - var isInDirectoryChecks = []; + var failedLookupChecks; + var startsWithPathChecks; + var isInDirectoryChecks; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -113753,9 +113710,12 @@ var ts; var resolvedModuleNames = new ts.Map(); var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache); var resolvedTypeReferenceDirectives = new ts.Map(); var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -113813,9 +113773,9 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.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(); @@ -113851,9 +113811,8 @@ var ts; isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -113880,7 +113839,7 @@ 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), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; @@ -113891,6 +113850,9 @@ var ts; // Default return the result from the first pass return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } function resolveNamesWithLocalCache(_a) { var _b; var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; @@ -113978,7 +113940,7 @@ var ts; redirectedReference: redirectedReference, cache: resolvedTypeReferenceDirectives, perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, - loader: ts.resolveTypeReferenceDirective, + loader: resolveTypeReferenceDirective, getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, }); @@ -114253,7 +114215,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -114271,8 +114233,8 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -114283,27 +114245,33 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(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. + var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { return resolution.failedLookupLocations.some(function (location) { var locationPath = resolutionHost.toPath(location); return ts.contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) || - isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, 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); })); }); } function closeTypeRootsWatch() { @@ -114524,7 +114492,7 @@ var ts; if (!baseUrl && !paths || relativePreference === 0 /* Relative */) { return relativePath; } - var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl; + var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -114539,7 +114507,9 @@ var ts; return nonRelative; } if (relativePreference === 3 /* ExternalNonRelative */) { - var projectDirectory = host.getCurrentDirectory(); + var projectDirectory = compilerOptions.configFilePath ? + ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName); var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory); var targetIsInternal = ts.startsWith(modulePath, projectDirectory); @@ -114614,9 +114584,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 links = host.getSymlinkCache ? host.getSymlinkCache() @@ -114639,10 +114609,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; } }); }); @@ -114773,7 +114743,7 @@ var ts; ts.startsWith(relativeToBaseUrl, prefix) && ts.endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } @@ -116374,12 +116344,19 @@ var ts; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); 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) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } + if (!compilerHost.resolveTypeReferenceDirectives) { + var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4); + }; + } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -116404,6 +116381,7 @@ var ts; projectErrorsReported: new ts.Map(), compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, + typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, // Mutable state buildOrder: undefined, readFileWithCache: function (f) { return host.readFile(f); }, @@ -116591,7 +116569,7 @@ var ts; function disableCache(state) { if (!state.cache) return; - var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache; + var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -116600,10 +116578,8 @@ var ts; compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear(); state.cache = undefined; } function clearProjectStatus(state, resolved) { @@ -116770,6 +116746,7 @@ var ts; return withProgramOrUndefined(action) || ts.emptyArray; } function createProgram() { + var _a, _b; ts.Debug.assert(program === undefined); if (state.options.dry) { reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -116789,7 +116766,8 @@ var ts; var host = state.host, compilerHost = state.compilerHost; state.projectCompilerOptions = config.options; // Update module resolution cache if needed - updateModuleResolutionCache(state, project, config); + (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { @@ -116964,7 +116942,7 @@ var ts; emitBundle(writeFile, customTransformers); break; case BuildStep.BuildInvalidatedProjectOfBundle: - ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; case BuildStep.QueueReferencingProjects: @@ -117106,31 +117084,6 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache(state, proj, config) { - if (!state.moduleResolutionCache) - return; - // Update module resolution cache if needed - var moduleResolutionCache = state.moduleResolutionCache; - var projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - // The own map will be for projectCompilerOptions - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - // Set correct own map - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - var ref = { - sourceFile: config.options.configFile, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time var tsconfigTime = ts.getModifiedTime(state.host, configFile); @@ -117143,6 +117096,7 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { + var force = !!state.options.force; var newestInputFileName = undefined; var newestInputFileTime = minimumDate; var host = state.host; @@ -117155,11 +117109,13 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = ts.getModifiedTime(host, inputFile); - host.getModifiedTime(inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + var inputTime = ts.getModifiedTime(host, inputFile); + host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } // Container if no files are specified in the project @@ -117178,36 +117134,38 @@ var ts; var missingOutputFileName; var newestDeclarationFileContentChangedTime = minimumDate; var isOutOfDateWithInputs = false; - 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 (isDeclarationFile(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + 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 (isDeclarationFile(output)) { + var outputModifiedTime = ts.getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } var pseudoUpToDate = false; @@ -117243,7 +117201,8 @@ var ts; }; } // Check oldest output file name only if there is no missing output file name - if (!missingOutputFileName) { + // (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) { @@ -117289,7 +117248,7 @@ var ts; if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -117431,7 +117390,7 @@ var ts; } } } - function build(state, project, cancellationToken, onlyReferences) { + function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -117443,7 +117402,7 @@ var ts; if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -117625,9 +117584,9 @@ var ts; function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: function (project, cancellationToken) { return build(state, project, cancellationToken); }, + build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); }, clean: function (project) { return clean(state, project); }, - buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); }, + buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, /*onlyReferences*/ true); }, cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); }, getNextInvalidatedProject: function (cancellationToken) { setupInitialBuild(state, cancellationToken); @@ -117717,6 +117676,9 @@ 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)); @@ -118856,7 +118818,7 @@ var ts; case 167 /* Constructor */: return "constructor" /* constructorImplementationElement */; case 160 /* TypeParameter */: return "type parameter" /* typeParameterElement */; case 292 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 161 /* Parameter */: return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 161 /* Parameter */: return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; case 261 /* ImportEqualsDeclaration */: case 266 /* ImportSpecifier */: case 271 /* ExportSpecifier */: @@ -119540,6 +119502,21 @@ var ts; return current; } } + /** + * Returns the first token where position is in [start, end), + * excluding `JsxText` tokens containing only whitespace. + */ + function findFirstNonJsxWhitespaceToken(sourceFile, position) { + var tokenAtPosition = getTokenAtPosition(sourceFile, position); + while (isWhiteSpaceOnlyJsxText(tokenAtPosition)) { + var nextToken = findNextToken(tokenAtPosition, tokenAtPosition.parent, sourceFile); + if (!nextToken) + return; + tokenAtPosition = nextToken; + } + return tokenAtPosition; + } + ts.findFirstNonJsxWhitespaceToken = findFirstNonJsxWhitespaceToken; /** * The token on the left of the position is the token that strictly includes the position * or sits to the left of the cursor if it is on a boundary. For example @@ -120534,6 +120511,14 @@ var ts; return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); } ts.operatorPart = operatorPart; + function parameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.parameterName); + } + ts.parameterNamePart = parameterNamePart; + function propertyNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.propertyName); + } + ts.propertyNamePart = propertyNamePart; function textOrKeywordPart(text) { var kind = ts.stringToToken(text); return kind === undefined @@ -120545,6 +120530,14 @@ var ts; return displayPart(text, ts.SymbolDisplayPartKind.text); } ts.textPart = textPart; + function typeAliasNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.aliasName); + } + ts.typeAliasNamePart = typeAliasNamePart; + function typeParameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.typeParameterName); + } + ts.typeParameterNamePart = typeParameterNamePart; function linkTextPart(text) { return displayPart(text, ts.SymbolDisplayPartKind.linkText); } @@ -120565,6 +120558,7 @@ var ts; } ts.linkPart = linkPart; function buildLinkParts(link, checker) { + var _a; var parts = [linkPart("{@link ")]; if (!link.name) { if (link.text) { @@ -120573,8 +120567,9 @@ var ts; } else { var symbol = checker === null || checker === void 0 ? void 0 : checker.getSymbolAtLocation(link.name); - if (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) { - parts.push(linkNamePart(link.name, symbol.valueDeclaration)); + var decl = (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) || ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]); + if (decl) { + parts.push(linkNamePart(link.name, decl)); if (link.text) { parts.push(linkTextPart(link.text)); } @@ -123854,6 +123849,7 @@ var ts; sourceDisplay: sourceDisplay, isSnippet: isSnippet, isPackageJsonImport: originIsPackageJsonImport(origin) || undefined, + isImportStatementCompletion: originIsResolvedExport(origin) || undefined, data: data, }; } @@ -124655,7 +124651,8 @@ var ts; return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined; } function tryGetGlobalSymbols() { - var result = tryGetObjectLikeCompletionSymbols() + var result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() + || tryGetObjectLikeCompletionSymbols() || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() @@ -124800,8 +124797,9 @@ var ts; } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 111 /* TypeOfKeyword */ && - (contextToken.parent.kind === 177 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + ((contextToken.kind === 111 /* TypeOfKeyword */ && + (contextToken.parent.kind === 177 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent))) || + (contextToken.kind === 127 /* AssertsKeyword */ && contextToken.parent.kind === 173 /* TypePredicate */)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { @@ -125018,6 +125016,25 @@ var ts; return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) || position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken))); } + function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() { + var typeLiteralNode = tryGetTypeLiteralNode(contextToken); + if (!typeLiteralNode) + return 0 /* Continue */; + var intersectionTypeNode = ts.isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : undefined; + var containerTypeNode = intersectionTypeNode || typeLiteralNode; + var containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker); + if (!containerExpectedType) + return 0 /* Continue */; + var containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode); + var members = getPropertiesForCompletion(containerExpectedType, typeChecker); + var existingMembers = getPropertiesForCompletion(containerActualType, typeChecker); + var existingMemberEscapedNames = new ts.Set(); + existingMembers.forEach(function (s) { return existingMemberEscapedNames.add(s.escapedName); }); + symbols = ts.filter(members, function (s) { return !existingMemberEscapedNames.has(s.escapedName); }); + completionKind = 0 /* ObjectPropertyDeclaration */; + isNewIdentifierLocation = true; + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in object literals and object binding patterns. * Relevant symbols are stored in the captured 'symbols' variable. @@ -125402,7 +125419,7 @@ var ts; case 41 /* AsteriskToken */: return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } - // If the previous token is keyword correspoding to class member completion keyword + // If the previous token is keyword corresponding to class member completion keyword // there will be completion available here if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; @@ -125437,6 +125454,31 @@ var ts; case 129 /* AsyncKeyword */: return ts.isPropertyDeclaration(contextToken.parent); } + // If we are inside a class declaration, and `constructor` is totally not present, + // but we request a completion manually at a whitespace... + var ancestorClassLike = ts.findAncestor(contextToken.parent, ts.isClassLike); + if (ancestorClassLike && contextToken === previousToken && isPreviousPropertyDeclarationTerminated(contextToken, position)) { + return false; // Don't block completions. + } + var ancestorPropertyDeclaraion = ts.getAncestor(contextToken.parent, 164 /* PropertyDeclaration */); + // If we are inside a class declaration and typing `constructor` after property declaration... + if (ancestorPropertyDeclaraion + && contextToken !== previousToken + && ts.isClassLike(previousToken.parent.parent) + // And the cursor is at the token... + && position <= previousToken.end) { + // If we are sure that the previous property declaration is terminated according to newline or semicolon... + if (isPreviousPropertyDeclarationTerminated(contextToken, previousToken.end)) { + return false; // Don't block completions. + } + else if (contextToken.kind !== 62 /* EqualsToken */ + // Should not block: `class C { blah = c/**/ }` + // But should block: `class C { blah = somewhat c/**/ }` and `class C { blah: SomeType c/**/ }` + && (ts.isInitializedProperty(ancestorPropertyDeclaraion) + || ts.hasType(ancestorPropertyDeclaraion))) { + return true; + } + } return ts.isDeclarationName(contextToken) && !ts.isShorthandPropertyAssignment(contextToken.parent) && !ts.isJsxAttribute(contextToken.parent) @@ -125444,6 +125486,11 @@ var ts; // If `contextToken !== previousToken`, this is `class C ex/**/`. && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } + function isPreviousPropertyDeclarationTerminated(contextToken, position) { + return contextToken.kind !== 62 /* EqualsToken */ && + (contextToken.kind === 26 /* SemicolonToken */ + || !ts.positionsAreOnSameLine(contextToken.end, position, sourceFile)); + } function isFunctionLikeButNotConstructor(kind) { return ts.isFunctionLikeKind(kind) && kind !== 167 /* Constructor */; } @@ -125849,6 +125896,12 @@ var ts; } if (!contextToken) return undefined; + // class C { blah; constructor/**/ } and so on + if (location.kind === 132 /* ConstructorKeyword */ + // class C { blah \n constructor/**/ } + || (ts.isIdentifier(contextToken) && ts.isPropertyDeclaration(contextToken.parent) && ts.isClassLike(location))) { + return ts.findAncestor(contextToken, ts.isClassLike); + } switch (contextToken.kind) { case 62 /* EqualsToken */: return undefined; @@ -125874,6 +125927,44 @@ var ts; ? contextToken.parent.parent : undefined; } } + function tryGetTypeLiteralNode(node) { + if (!node) + return undefined; + var parent = node.parent; + switch (node.kind) { + case 18 /* OpenBraceToken */: + if (ts.isTypeLiteralNode(parent)) { + return parent; + } + break; + case 26 /* SemicolonToken */: + case 27 /* CommaToken */: + case 78 /* Identifier */: + if (parent.kind === 163 /* PropertySignature */ && ts.isTypeLiteralNode(parent.parent)) { + return parent.parent; + } + break; + } + return undefined; + } + function getConstraintOfTypeArgumentProperty(node, checker) { + if (!node) + return undefined; + if (ts.isTypeNode(node) && ts.isTypeReferenceType(node.parent)) { + return checker.getTypeArgumentConstraint(node); + } + var t = getConstraintOfTypeArgumentProperty(node.parent, checker); + if (!t) + return undefined; + switch (node.kind) { + case 163 /* PropertySignature */: + return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); + case 184 /* IntersectionType */: + case 178 /* TypeLiteral */: + case 183 /* UnionType */: + return t; + } + } // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes function isFromObjectTypeDeclaration(node) { return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); @@ -125933,7 +126024,8 @@ var ts; if (type) { return type; } - if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { + if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ && node === node.parent.left) { + // Object literal is assignment pattern: ({ | } = x) return typeChecker.getTypeAtLocation(node.parent); } return undefined; @@ -126434,6 +126526,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function isDocumentRegistryEntry(entry) { + return !!entry.sourceFile; + } function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); } @@ -126450,10 +126545,16 @@ var ts; var entries = buckets.get(name); var sourceFiles = []; entries.forEach(function (entry, name) { - sourceFiles.push({ - name: name, - refCount: entry.languageServiceRefCount - }); + if (isDocumentRegistryEntry(entry)) { + sourceFiles.push({ + name: name, + scriptKind: entry.sourceFile.scriptKind, + refCount: entry.languageServiceRefCount + }); + } + else { + entry.forEach(function (value, scriptKind) { return sourceFiles.push({ name: name, scriptKind: scriptKind, refCount: value.languageServiceRefCount }); }); + } }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); return { @@ -126479,10 +126580,17 @@ var ts; function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } + 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:" + scriptKind + " and sourceFile.scriptKind: " + (entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind) + ", !entry: " + !entry); + return entry; + } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); - var entry = bucket.get(path); + scriptKind = ts.ensureScriptKind(fileName, scriptKind); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; + var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -126491,7 +126599,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 0 }; - bucket.set(path, entry); + setBucketEntry(); } } if (!entry) { @@ -126504,7 +126612,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 1, }; - bucket.set(path, entry); + setBucketEntry(); } else { // We have an entry for this file. However, it may be for a different version of @@ -126527,25 +126635,49 @@ var ts; } ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; + function setBucketEntry() { + if (!bucketEntry) { + bucket.set(path, entry); + } + else if (isDocumentRegistryEntry(bucketEntry)) { + var scriptKindMap = new ts.Map(); + scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry); + scriptKindMap.set(scriptKind, entry); + bucket.set(path, scriptKindMap); + } + else { + bucketEntry.set(scriptKind, entry); + } + } } - function releaseDocument(fileName, compilationSettings) { + function releaseDocument(fileName, compilationSettings, scriptKind) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); + return releaseDocumentWithKey(path, key, scriptKind); } - function releaseDocumentWithKey(path, key) { + function releaseDocumentWithKey(path, key, scriptKind) { var bucket = ts.Debug.checkDefined(buckets.get(key)); - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.delete(path); + if (isDocumentRegistryEntry(bucketEntry)) { + bucket.delete(path); + } + else { + bucketEntry.delete(scriptKind); + if (bucketEntry.size === 1) { + bucket.set(path, ts.firstDefinedIterator(bucketEntry.values(), ts.identity)); + } + } } } - function getLanguageServiceRefCounts(path) { + function getLanguageServiceRefCounts(path, scriptKind) { return ts.arrayFrom(buckets.entries(), function (_a) { var key = _a[0], bucket = _a[1]; - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); return [key, entry && entry.languageServiceRefCount]; }); } @@ -126975,13 +127107,13 @@ var ts; function getExport() { var _a; var parent = node.parent; - var grandParent = parent.parent; + var grandparent = parent.parent; if (symbol.exportSymbol) { if (parent.kind === 202 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandParent) - ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandparent) + ? getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ false) : undefined; } else { @@ -127011,15 +127143,15 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(grandParent)) { - return getExportAssignmentExport(grandParent); + else if (ts.isExportAssignment(grandparent)) { + return getExportAssignmentExport(grandparent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(grandParent)) { - return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandparent)) { + return getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ true); } else if (ts.isJSDocTypedefTag(parent)) { return exportInfo(symbol, 0 /* Named */); @@ -127027,9 +127159,10 @@ var ts; } function getExportAssignmentExport(ex) { // Get the symbol for the `export =` node; its parent is the module it's the export of. - var exportingModuleSymbol = ts.Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + if (!ex.symbol.parent) + return undefined; var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; - return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: ex.symbol.parent, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; @@ -127981,9 +128114,9 @@ var ts; // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); } - else if (node && node.kind === 87 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */) { + else if (node && node.kind === 87 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) { addReference(node, symbol, state); - searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); @@ -128198,7 +128331,9 @@ var ts; for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { var node = _d[_c]; // Import specifiers should be handled by importSearches - if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + var symbol = checker.getSymbolAtLocation(node); + var hasExportAssignmentDeclaration = ts.some(symbol === null || symbol === void 0 ? void 0 : symbol.declarations, function (d) { return ts.tryCast(d, ts.isExportAssignment) ? true : false; }); + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) { cb(node); } } @@ -128505,6 +128640,10 @@ var ts; default: ts.Debug.assertNever(state.specialSearchKind); } + // Use the parent symbol if the location is commonjs require syntax on javascript files only. + referenceSymbol = ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 199 /* BindingElement */ && ts.isRequireVariableDeclaration(referenceLocation.parent) + ? referenceLocation.parent.symbol + : referenceSymbol; getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { @@ -128872,6 +129011,8 @@ var ts; case 166 /* MethodDeclaration */: case 165 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { + staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning object literals break; } // falls through @@ -128912,7 +129053,8 @@ var ts; return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; case 222 /* ClassExpression */: case 253 /* ClassDeclaration */: - // Make sure the container belongs to the same class + case 201 /* ObjectLiteralExpression */: + // Make sure the container belongs to the same class/object literals // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getSyntacticModifierFlags(container) & 32 /* Static */) === staticFlag; case 298 /* SourceFile */: @@ -130040,7 +130182,7 @@ var ts; end: node.getEnd(), fileName: node.text }, - unverified: !!verifiedFileName, + unverified: !verifiedFileName, }; } } @@ -130193,7 +130335,38 @@ var ts; var sourceFile = name.getSourceFile(); var textSpan = ts.createTextSpanFromNode(name, sourceFile); return __assign(__assign({ fileName: sourceFile.fileName, textSpan: textSpan, kind: symbolKind, name: symbolName, containerKind: undefined, // TODO: GH#18217 - containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !checker.isDeclarationVisible(declaration) }); + containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !isDefinitionVisible(checker, declaration) }); + } + function isDefinitionVisible(checker, declaration) { + if (checker.isDeclarationVisible(declaration)) + return true; + if (!declaration.parent) + return false; + // Variable initializers are visible if variable is visible + if (ts.hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) + return isDefinitionVisible(checker, declaration.parent); + // Handle some exceptions here like arrow function, members of class and object literal expression which are technically not visible but we want the definition to be determined by its parent + switch (declaration.kind) { + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + // Private/protected properties/methods are not visible + if (ts.hasEffectiveModifier(declaration, 8 /* Private */)) + return false; + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 167 /* Constructor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + return isDefinitionVisible(checker, declaration.parent); + default: + return false; + } } function createDefinitionFromSignatureDeclaration(typeChecker, decl) { return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); @@ -130286,6 +130459,7 @@ var ts; "kind", "lends", "license", + "link", "listens", "member", "memberof", @@ -130379,8 +130553,9 @@ var ts; return ts.flatMap(comment, function (node) { return node.kind === 313 /* JSDocText */ ? [ts.textPart(node.text)] : ts.buildLinkParts(node, checker); }); } function getCommentDisplayParts(tag, checker) { - var comment = tag.comment; - switch (tag.kind) { + var comment = tag.comment, kind = tag.kind; + var namePart = getTagNameDisplayPart(kind); + switch (kind) { case 319 /* JSDocImplementsTag */: return withNode(tag.class); case 318 /* JSDocAugmentsTag */: @@ -130395,7 +130570,9 @@ var ts; case 330 /* JSDocParameterTag */: case 336 /* JSDocSeeTag */: var name = tag.name; - return name ? withNode(name) : comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); + return name ? withNode(name) + : comment === undefined ? undefined + : getDisplayPartsFromComment(comment, checker); default: return comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); } @@ -130403,7 +130580,32 @@ var ts; return addComment(node.getText()); } function addComment(s) { - return comment ? __spreadArray([ts.textPart(s), ts.spacePart()], getDisplayPartsFromComment(comment, checker)) : [ts.textPart(s)]; + if (comment) { + if (s.match(/^https?$/)) { + return __spreadArray([ts.textPart(s)], getDisplayPartsFromComment(comment, checker)); + } + else { + return __spreadArray([namePart(s), ts.spacePart()], getDisplayPartsFromComment(comment, checker)); + } + } + else { + return [ts.textPart(s)]; + } + } + } + function getTagNameDisplayPart(kind) { + switch (kind) { + case 330 /* JSDocParameterTag */: + return ts.parameterNamePart; + case 337 /* JSDocPropertyTag */: + return ts.propertyNamePart; + case 334 /* JSDocTemplateTag */: + return ts.typeParameterNamePart; + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + return ts.typeAliasNamePart; + default: + return ts.textPart; } } function getJSDocTagNameCompletions() { @@ -131656,9 +131858,9 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences) { + function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); @@ -131693,26 +131895,35 @@ var ts; ? coalesce(importGroup) : importGroup; }); - // Delete or replace the first import. + // Delete all nodes if there are no imports. if (newImportDecls.length === 0) { - changeTracker.delete(sourceFile, oldImportDecls[0]); + // Consider the first node to have trailingTrivia as we want to exclude the + // "header" comment. + changeTracker.deleteNodes(sourceFile, oldImportDecls, { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, /*hasTrailingComment*/ true); } else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + var replaceOptions = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - // Delete any subsequent imports. - for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + }; + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions); + var hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions); + changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, hasTrailingComment); } } } OrganizeImports.organizeImports = organizeImports; - function removeUnusedImports(oldImports, sourceFile, program) { + function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { + // As a precaution, consider unused import detection to be destructive (GH #43051) + if (skipDestructiveCodeActions) { + return oldImports; + } var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); var jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile); @@ -133190,7 +133401,7 @@ var ts; function getRenameInfo(program, sourceFile, position, options) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); if (renameInfo) { return renameInfo; } @@ -133198,7 +133409,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -133218,7 +133429,7 @@ var ts; if (!declarations || declarations.length === 0) return; // Disallow rename for elements that are defined in the standard TypeScript library. - if (declarations.some(isDefinedInLibraryFile)) { + if (declarations.some(function (declaration) { return isDefinedInLibraryFile(program, declaration); })) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; @@ -133236,6 +133447,10 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), node, sourceFile); } + function isDefinedInLibraryFile(program, declaration) { + var sourceFile = declaration.getSourceFile(); + return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); @@ -134386,7 +134601,7 @@ var ts; diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } } - if (ts.isFunctionLikeDeclaration(node)) { + if (canBeConvertedToAsync(node)) { addConvertToAsyncFunctionDiagnostics(node, checker, diags); } node.forEachChild(check); @@ -134443,11 +134658,11 @@ var ts; returnsPromise(node, checker); } function returnsPromise(node, checker) { - var functionType = checker.getTypeAtLocation(node); - var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); - var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + var signature = checker.getSignatureFromDeclaration(node); + var returnType = signature ? checker.getReturnTypeOfSignature(signature) : undefined; return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } + ts.returnsPromise = returnsPromise; function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } @@ -134529,6 +134744,18 @@ var ts; } return false; } + function canBeConvertedToAsync(node) { + switch (node.kind) { + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + return true; + default: + return false; + } + } + ts.canBeConvertedToAsync = canBeConvertedToAsync; })(ts || (ts = {})); /* @internal */ var ts; @@ -134700,7 +134927,7 @@ var ts; symbolKind = "property" /* memberVariableElement */; } var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (location.parent && location.parent.kind === 202 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing @@ -138324,7 +138551,9 @@ var ts; function getAdjustedRange(sourceFile, startNode, endNode, options) { return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - function getAdjustedStartPosition(sourceFile, node, options) { + function getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment) { + var _a, _b; + if (hasTrailingComment === void 0) { hasTrailingComment = false; } var leadingTriviaOption = options.leadingTriviaOption; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); @@ -138355,6 +138584,15 @@ var ts; // when b is deleted - we delete it return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start; } + // if node has a trailing comments, use comment end position as the text has already been included. + if (hasTrailingComment) { + // Check first for leading comments as if the node is the first import, we want to exclude the trivia; + // otherwise we get the trailing comments. + var comment = ((_a = ts.getLeadingCommentRanges(sourceFile.text, fullStart)) === null || _a === void 0 ? void 0 : _a[0]) || ((_b = ts.getTrailingCommentRanges(sourceFile.text, fullStart)) === null || _b === void 0 ? void 0 : _b[0]); + if (comment) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } // get start position of the line following the line that contains fullstart position // (but only if the fullstart isn't the very beginning of the file) var nextLineStart = fullStart > 0 ? 1 : 0; @@ -138363,6 +138601,35 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } + /** Return the end position of a multiline comment of it is on another line; otherwise returns `undefined`; */ + function getEndPositionOfMultilineTrailingComment(sourceFile, node, options) { + var end = node.end; + var trailingTriviaOption = options.trailingTriviaOption; + if (trailingTriviaOption === TrailingTriviaOption.Include) { + // If the trailing comment is a multiline comment that extends to the next lines, + // return the end of the comment and track it for the next nodes to adjust. + var comments = ts.getTrailingCommentRanges(sourceFile.text, end); + if (comments) { + var nodeEndLine = ts.getLineOfLocalPosition(sourceFile, node.end); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + // Single line can break the loop as trivia will only be this line. + // Comments on subsequest lines are also ignored. + if (comment.kind === 2 /* SingleLineCommentTrivia */ || ts.getLineOfLocalPosition(sourceFile, comment.pos) > nodeEndLine) { + break; + } + // Get the end line of the comment and compare against the end line of the node. + // If the comment end line position and the multiline comment extends to multiple lines, + // then is safe to return the end position. + var commentEndLine = ts.getLineOfLocalPosition(sourceFile, comment.end); + if (commentEndLine > nodeEndLine) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } + } + } + return undefined; + } function getAdjustedEndPosition(sourceFile, node, options) { var _a; var end = node.end; @@ -138378,6 +138645,10 @@ var ts; } return end; } + var multilineEndPosition = getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + if (multilineEndPosition) { + return multilineEndPosition; + } var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd @@ -138389,13 +138660,6 @@ var ts; function isSeparator(node, candidate) { return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 201 /* ObjectLiteralExpression */)); } - function spaces(count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += " "; - } - return s; - } function isThisTypeAnnotatable(containingFunction) { return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction); } @@ -138440,6 +138704,17 @@ var ts; if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); }; + ChangeTracker.prototype.deleteNodes = function (sourceFile, nodes, options, hasTrailingComment) { + if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } + // When deleting multiple nodes we need to track if the end position is including multiline trailing comments. + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment); + var end = getAdjustedEndPosition(sourceFile, node, options); + this.deleteRange(sourceFile, { pos: pos, end: end }); + hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + } + }; ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; @@ -138482,6 +138757,10 @@ var ts; if (options === void 0) { options = useNonAdjustedPositions; } this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; + ChangeTracker.prototype.nodeHasTrailingComment = function (sourceFile, oldNode, configurableEnd) { + if (configurableEnd === void 0) { configurableEnd = useNonAdjustedPositions; } + return !!getEndPositionOfMultilineTrailingComment(sourceFile, oldNode, configurableEnd); + }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { var next = ts.findNextToken(node, node.parent, sourceFile); return next && next.kind === 27 /* CommaToken */ ? next : undefined; @@ -138825,47 +139104,22 @@ var ts; // a, b, c // create change for adding 'e' after 'a' as // - find start of next element after a (it is b) - // - use this start as start and end position in final change - // - build text of change by formatting the text of node + separator + whitespace trivia of b + // - use next element start as start and end position in final change + // - build text of change by formatting the text of node + whitespace trivia of b // in multiline case it will work as // a, // b, // c, // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') - // a,* - // ***insertedtext# + // a, + // insertedtext# // ###b, // c, - // find line and character of the next element - var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); - // find line and character of the token that precedes next element (usually it is separator) - var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); - var prefix = void 0; - var startPos = void 0; - if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { - // next element is located on the same line with separator: - // a,$$$$b - // ^ ^ - // | |-next element - // |-separator - // where $$$ is some leading trivia - // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces - // a, x,$$$$b - // ^ ^ ^ - // | | |-next element - // | |-new inserted node padded with spaces - // |-separator - startPos = nextToken.end; - prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); - } - else { - // next element is located on different line that separator - // let insert position be the beginning of the line that contains next element - startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); - } + var nextNode = containingList[index + 1]; + var startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart()); // write separator and leading trivia of the next element as suffix - var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, startPos); + this.insertNodesAt(sourceFile, startPos, [newNode], { suffix: suffix }); } } else { @@ -139396,7 +139650,9 @@ var ts; case 261 /* ImportEqualsDeclaration */: var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); // For first import, leave header comment in place, otherwise only delete JSDoc comments - deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + deleteNode(changes, sourceFile, node, { + leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine, + }); break; case 199 /* BindingElement */: var pattern = node.parent; @@ -139822,7 +140078,7 @@ var ts; ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code, - ts.Diagnostics.This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, ts.Diagnostics.Type_0_is_not_an_array_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators.code, @@ -140713,7 +140969,7 @@ var ts; functionToConvert = tokenAtPosition.parent.initializer; } else { - functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.canBeConvertedToAsync); } if (!functionToConvert) { return; @@ -140722,6 +140978,9 @@ var ts; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); + if (!ts.returnsPromise(functionToConvertRenamed, checker)) { + return; + } var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray; var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { @@ -142339,6 +142598,10 @@ var ts; if (!importClause || !ts.isStringLiteralLike(declaration.moduleSpecifier)) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; + // A type-only import may not have both a default and named imports, so the only way a name can + // be added to an existing type-only import is adding a named import to existing named bindings. + if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) + return undefined; return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 265 /* NamedImports */) ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.text, canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; @@ -142872,7 +143135,8 @@ var ts; ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, - ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code ]; var errorCodeFixIdMap = (_a = {}, _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code] = [ @@ -142881,6 +143145,9 @@ var ts; _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code] = [ ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers ], + _a[ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, + ], _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code] = [ ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers ], @@ -142919,6 +143186,7 @@ var ts; switch (errorCode) { case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: @@ -142928,16 +143196,23 @@ var ts; } } function doAddOverrideModifierChange(changeTracker, sourceFile, pos) { - var classElement = findContainerClassElement(sourceFile, pos); - changeTracker.insertModifierBefore(sourceFile, 156 /* OverrideKeyword */, classElement); + var classElement = findContainerClassElementLike(sourceFile, pos); + var modifiers = classElement.modifiers || ts.emptyArray; + var staticModifier = ts.find(modifiers, ts.isStaticModifier); + var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var modifierPos = staticModifier ? staticModifier.end : + accessibilityModifier ? accessibilityModifier.end : + classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + var options = accessibilityModifier || staticModifier ? { prefix: " " } : { suffix: " " }; + changeTracker.insertModifierAt(sourceFile, modifierPos, 156 /* OverrideKeyword */, options); } function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { - var classElement = findContainerClassElement(sourceFile, pos); + var classElement = findContainerClassElementLike(sourceFile, pos); var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 156 /* OverrideKeyword */; }); ts.Debug.assertIsDefined(overrideModifier); changeTracker.deleteModifier(sourceFile, overrideModifier); } - function isClassElementHasJSDoc(node) { + function isClassElementLikeHasJSDoc(node) { switch (node.kind) { case 167 /* Constructor */: case 164 /* PropertyDeclaration */: @@ -142945,18 +143220,20 @@ var ts; case 168 /* GetAccessor */: case 169 /* SetAccessor */: return true; + case 161 /* Parameter */: + return ts.isParameterPropertyDeclaration(node, node.parent); default: return false; } } - function findContainerClassElement(sourceFile, pos) { + function findContainerClassElementLike(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); var classElement = ts.findAncestor(token, function (node) { if (ts.isClassLike(node)) return "quit"; - return isClassElementHasJSDoc(node); + return isClassElementLikeHasJSDoc(node); }); - ts.Debug.assert(classElement && isClassElementHasJSDoc(classElement)); + ts.Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); return classElement; } })(codefix = ts.codefix || (ts.codefix = {})); @@ -143673,11 +143950,11 @@ var ts; var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, 1 /* NoTruncation */); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */) : undefined; } return typeNode || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } @@ -144807,7 +145084,7 @@ var ts; (function (codefix) { var fixId = "fixMissingCallParentheses"; var errorCodes = [ - ts.Diagnostics.This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -147538,7 +147815,7 @@ var ts; 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 flags = ts.getSyntacticModifierFlags(exportNode); + var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ExportDefault */ : 0 /* None */); var wasDefault = !!(flags & 512 /* Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { @@ -147566,6 +147843,11 @@ var ts; ts.Debug.assert(!wasDefault, "Can't have a default flag here"); return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } + case 267 /* ExportAssignment */: { + var node = exportNode; + var exp = node.expression; + return node.isExportEquals ? undefined : { exportNode: node, exportName: exp, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol }; + } default: return undefined; } @@ -147577,7 +147859,14 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + 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]))); + } + else { + changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + } } else { var exportKeyword = ts.Debug.checkDefined(ts.findModifier(exportNode, 92 /* ExportKeyword */), "Should find an export keyword in modifier list"); @@ -147604,7 +147893,7 @@ var ts; changes.insertNodeAfter(exportingSourceFile, exportNode, ts.factory.createExportDefault(ts.factory.createIdentifier(exportName.text))); break; default: - ts.Debug.assertNever(exportNode, "Unexpected exportNode kind " + exportNode.kind); + ts.Debug.fail("Unexpected exportNode kind " + exportNode.kind); } } } @@ -148533,7 +148822,7 @@ var ts; return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } var cursorRequest = length === 0 && invoked; - var startToken = ts.getTokenAtPosition(sourceFile, span.start); + var startToken = ts.findFirstNonJsxWhitespaceToken(sourceFile, span.start); var endToken = ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)); /* If the refactoring command is invoked through a keyboard action it's safe to assume that the user is actively looking for refactoring actions at the span location. As they may not know the exact range that will trigger a refactoring, we expand the @@ -152342,8 +152631,8 @@ var ts; var list = createNode(338 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; addSyntheticNodes(list._children, pos, node.pos, parent); list._children.push(node); pos = node.end; @@ -152785,7 +153074,7 @@ var ts; break; case 161 /* Parameter */: // Only consider parameter properties - if (!ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { break; } // falls through @@ -153366,7 +153655,7 @@ var ts; // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); } function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); @@ -153411,8 +153700,13 @@ 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" - ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind."); - return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + 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); + } } // We didn't already have the file. Fall through and acquire it from the registry. } @@ -153441,7 +153735,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); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); }); program = undefined; // TODO: GH#18217 } @@ -153541,7 +153835,7 @@ var ts; function shouldGetType(sourceFile, node, position) { switch (node.kind) { case 78 /* Identifier */: - return !ts.isLabelName(node) && !ts.isTagName(node); + return !ts.isLabelName(node) && !ts.isTagName(node) && !ts.isConstTypeReference(node.parent); case 202 /* PropertyAccessExpression */: case 158 /* QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` @@ -153707,15 +154001,7 @@ var ts; function getNavigationTree(fileName) { return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); } - function isTsOrTsxFile(fileName) { - var kind = ts.getScriptKind(fileName, host); - return kind === 3 /* TS */ || kind === 4 /* TSX */; - } function getSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return []; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "2020" /* TwentyTwenty */) { @@ -153726,10 +154012,6 @@ var ts; } } function getEncodedSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return { spans: [], endOfLineState: 0 /* None */ }; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "original" /* Original */) { @@ -153820,13 +154102,13 @@ var ts; var formatContext = ts.formatting.getFormatContext(formatOptions, host); return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions, preferences) { + function organizeImports(args, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - ts.Debug.assert(scope.type === "file"); - var sourceFile = getValidSourceFile(scope.fileName); + ts.Debug.assert(args.type === "file"); + var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 56e1d342d9697..2d44d601a4731 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -540,7 +540,7 @@ declare namespace ts { Override = 16384, HasComputedFlags = 536870912, AccessibilityModifier = 28, - ParameterPropertyModifier = 92, + ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, TypeScriptModifier = 18654, ExportDefault = 513, @@ -563,7 +563,7 @@ declare namespace ts { } export interface JSDocContainer { } - export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; + export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | EmptyStatement | DebuggerStatement | Block | VariableStatement | ExpressionStatement | IfStatement | DoStatement | WhileStatement | ForStatement | ForInStatement | ForOfStatement | BreakStatement | ContinueStatement | ReturnStatement | WithStatement | SwitchStatement | LabeledStatement | ThrowStatement | TryStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; 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; @@ -1380,7 +1380,7 @@ declare namespace ts { readonly containsOnlyTriviaWhiteSpaces: boolean; } export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; - export interface Statement extends Node { + export interface Statement extends Node, JSDocContainer { _statementBrand: any; } export interface NotEmittedStatement extends Statement { @@ -1408,11 +1408,11 @@ declare namespace ts { readonly kind: SyntaxKind.Block; readonly statements: NodeArray; } - export interface VariableStatement extends Statement, JSDocContainer { + export interface VariableStatement extends Statement { readonly kind: SyntaxKind.VariableStatement; readonly declarationList: VariableDeclarationList; } - export interface ExpressionStatement extends Statement, JSDocContainer { + export interface ExpressionStatement extends Statement { readonly kind: SyntaxKind.ExpressionStatement; readonly expression: Expression; } @@ -1493,7 +1493,7 @@ declare namespace ts { readonly statements: NodeArray; } export type CaseOrDefaultClause = CaseClause | DefaultClause; - export interface LabeledStatement extends Statement, JSDocContainer { + export interface LabeledStatement extends Statement { readonly kind: SyntaxKind.LabeledStatement; readonly label: Identifier; readonly statement: Statement; @@ -1613,7 +1613,7 @@ declare namespace ts { readonly parent: ImportEqualsDeclaration; readonly expression: Expression; } - export interface ImportDeclaration extends Statement, JSDocContainer { + export interface ImportDeclaration extends Statement { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; readonly importClause?: ImportClause; @@ -2291,8 +2291,7 @@ declare namespace ts { IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, - InInitialEntityName = 16777216, - InReverseMappedType = 33554432 + InInitialEntityName = 16777216 } export enum TypeFormatFlags { None = 0, @@ -2560,15 +2559,15 @@ declare namespace ts { ObjectLiteral = 128, EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, - ContainsSpread = 1024, - ReverseMapped = 2048, - JsxAttributes = 4096, - MarkerType = 8192, - JSLiteral = 16384, - FreshLiteral = 32768, - ArrayLiteral = 65536, - ObjectRestType = 131072, + ReverseMapped = 1024, + JsxAttributes = 2048, + MarkerType = 4096, + JSLiteral = 8192, + FreshLiteral = 16384, + ArrayLiteral = 32768, ClassOrInterface = 3, + ContainsSpread = 4194304, + ObjectRestType = 8388608, } export interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2682,6 +2681,7 @@ declare namespace ts { type: Type; } export interface SubstitutionType extends InstantiableType { + objectFlags: ObjectFlags; baseType: Type; substitute: Type; } @@ -2706,16 +2706,17 @@ declare namespace ts { export enum InferencePriority { NakedTypeVariable = 1, SpeculativeTuple = 2, - HomomorphicMappedType = 4, - PartialHomomorphicMappedType = 8, - MappedTypeConstraint = 16, - ContravariantConditional = 32, - ReturnType = 64, - LiteralKeyof = 128, - NoConstraints = 256, - AlwaysStrict = 512, - MaxValue = 1024, - PriorityImpliesCombination = 208, + SubstituteSource = 4, + HomomorphicMappedType = 8, + PartialHomomorphicMappedType = 16, + MappedTypeConstraint = 32, + ContravariantConditional = 64, + ReturnType = 128, + LiteralKeyof = 256, + NoConstraints = 512, + AlwaysStrict = 1024, + MaxValue = 2048, + PriorityImpliesCombination = 416, Circularity = -1 } /** @deprecated Use FileExtensionInfo instead. */ @@ -4708,13 +4709,13 @@ declare namespace ts { export {}; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; + export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -4723,30 +4724,46 @@ declare namespace ts { * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResolutionCache, PackageJsonInfoCache { + } /** - * Cached module resolutions per containing directory. + * Cached resolutions per containing directory. * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ - interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + export interface PerDirectoryResolutionCache { + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + clear(): void; + /** + * Updates with the current compilerOptions the cache will operate with. + * This updates the redirects map as well if needed so module resolutions are cached if they can across the projects + */ + update(options: CompilerOptions): void; + } + export interface ModuleResolutionCache extends PerDirectoryResolutionCache, NonRelativeModuleNameResolutionCache, PackageJsonInfoCache { + getPackageJsonInfoCache(): PackageJsonInfoCache; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ - interface NonRelativeModuleNameResolutionCache { + export interface NonRelativeModuleNameResolutionCache extends PackageJsonInfoCache { getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } - interface PerModuleNameCache { + export interface PackageJsonInfoCache { + clear(): void; + } + export interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } - function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; - function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; + export function createTypeReferenceDirectiveResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions, packageJsonInfoCache?: PackageJsonInfoCache): TypeReferenceDirectiveResolutionCache; + export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; + export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export {}; } declare namespace ts { /** @@ -5202,9 +5219,9 @@ declare namespace ts { interface SolutionBuilderWithWatchHost extends SolutionBuilderHostBase, WatchHost { } interface SolutionBuilder { - build(project?: string, cancellationToken?: CancellationToken): ExitStatus; + build(project?: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; clean(project?: string): ExitStatus; - buildReferences(project: string, cancellationToken?: CancellationToken): ExitStatus; + buildReferences(project: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; cleanReferences(project?: string): ExitStatus; getNextInvalidatedProject(cancellationToken?: CancellationToken): InvalidatedProject | undefined; } @@ -5650,7 +5667,7 @@ declare namespace ts { applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; + organizeImports(args: OrganizeImportsArgs, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; @@ -5667,7 +5684,9 @@ declare namespace ts { type: "file"; fileName: string; } - type OrganizeImportsScope = CombinedCodeFixScope; + interface OrganizeImportsArgs extends CombinedCodeFixScope { + skipDestructiveCodeActions?: boolean; + } type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; interface GetCompletionsAtPositionOptions extends UserPreferences { /** @@ -6196,6 +6215,7 @@ declare namespace ts { isRecommended?: true; isFromUncheckedFile?: true; isPackageJsonImport?: true; + isImportStatementCompletion?: true; /** * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, * that allows TS Server to look up the symbol represented by the completion item, disambiguating @@ -6517,8 +6537,23 @@ declare namespace ts { * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file */ + /**@deprecated pass scriptKind for correctness */ releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @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 + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind): void; + /** + * @deprecated pass scriptKind for correctness */ releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind): void; reportStats(): string; } type DocumentRegistryBucketKey = string & { diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index b192a23a409d0..958c98542437b 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -290,7 +290,7 @@ var ts; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-beta"; + ts.version = "4.3.1-rc"; /* @internal */ var Comparison; (function (Comparison) { @@ -2856,11 +2856,11 @@ var ts; this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : - this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" : + this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; - var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0; + var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); } }, @@ -3881,7 +3881,7 @@ var ts; }; } var reverseMappedProperties = {}; - if (objectFlags & 2048 /* ReverseMapped */) { + if (objectFlags & 1024 /* ReverseMapped */) { var reverseMappedType = type; reverseMappedProperties = { reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id, @@ -4422,7 +4422,7 @@ var ts; 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. - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 18654] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; @@ -4623,7 +4623,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; - NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -4976,6 +4975,9 @@ var ts; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags + // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check + // for a certain TypeFlags value to determine their meaning. var ObjectFlags; (function (ObjectFlags) { ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; @@ -4988,50 +4990,59 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; - ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; - ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; - ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; - ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; - ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; - ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 1024] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 2048] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 4096] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 8192] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 16384] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ArrayLiteral"] = 32768] = "ArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 262144] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; + ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 1048576] = "CouldContainTypeVariablesComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; + ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 2097152] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags"; + // Object flags that uniquely identify the kind of ObjectType /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; + ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask"; + // Flags that require TypeFlags.Object + ObjectFlags[ObjectFlags["ContainsSpread"] = 4194304] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 8388608] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone"; + // Flags that require TypeFlags.Object and ObjectFlags.Reference /* @internal */ - ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated"; /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists"; + // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; + ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; + ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; - // Object flags that uniquely identify the kind of ObjectType + ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + // Flags that require TypeFlags.Union + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 67108864] = "ContainsIntersections"; + // Flags that require TypeFlags.Intersection /* @internal */ - ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask"; + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 67108864] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 134217728] = "IsNeverIntersection"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -5105,16 +5116,17 @@ var ts; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple"; - InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType"; - InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType"; - InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint"; - InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional"; - InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType"; - InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof"; - InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict"; - InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue"; - InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination"; + InferencePriority[InferencePriority["SubstituteSource"] = 4] = "SubstituteSource"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 8] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 16] = "PartialHomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 32] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ContravariantConditional"] = 64] = "ContravariantConditional"; + InferencePriority[InferencePriority["ReturnType"] = 128] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 256] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 512] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 1024] = "AlwaysStrict"; + InferencePriority[InferencePriority["MaxValue"] = 2048] = "MaxValue"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 416] = "PriorityImpliesCombination"; InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); /* @internal */ @@ -8051,7 +8063,7 @@ var ts; A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), - An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), @@ -8077,6 +8089,7 @@ var ts; A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), @@ -8163,7 +8176,7 @@ var ts; Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."), - The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."), + The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8205,6 +8218,7 @@ var ts; The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), + Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."), 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), @@ -8453,14 +8467,13 @@ var ts; The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), - Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), @@ -8483,17 +8496,17 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), @@ -8578,7 +8591,7 @@ var ts; Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), @@ -8586,14 +8599,14 @@ var ts; _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), - A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), @@ -8655,7 +8668,7 @@ var ts; The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), - This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_2774", "This condition will always return true since this function appears to always be defined. Did you mean to call it instead?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), @@ -8682,7 +8695,7 @@ var ts; The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), - This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined_2801", "This condition will always return true since this '{0}' appears to always be defined."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), @@ -8691,6 +8704,9 @@ var ts; This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), + Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), + Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), 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}'."), @@ -8788,7 +8804,7 @@ var ts; This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), - This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_becaus_4115", "This parameter property must be rewritten as a property declaration with an 'override' modifier because it overrides a member in base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), 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."), @@ -8824,7 +8840,7 @@ var ts; Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), - Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), @@ -8837,12 +8853,14 @@ var ts; Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), - A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -9066,7 +9084,11 @@ var ts; Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), - Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -9114,6 +9136,7 @@ var ts; _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), 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."), @@ -9155,7 +9178,7 @@ var ts; Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -9195,7 +9218,7 @@ var ts; JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), @@ -9880,11 +9903,11 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; /* @internal */ - function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { - if (stopAtComments === void 0) { stopAtComments = false; } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (ts.positionIsSynthesized(pos)) { return pos; } + var canConsumeStar = false; // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -9899,6 +9922,7 @@ var ts; if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case 9 /* tab */: case 11 /* verticalTab */: @@ -9918,6 +9942,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { @@ -9929,6 +9954,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } break; @@ -9938,12 +9964,21 @@ var ts; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; case 35 /* hash */: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42 /* asterisk */: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -11994,7 +12029,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; + return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -12310,7 +12345,7 @@ var ts; if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } ts.getNameOfDeclaration = getNameOfDeclaration; /*@internal*/ @@ -12865,7 +12900,7 @@ var ts; ts.isModifierKind = isModifierKind; /* @internal */ function isParameterPropertyModifier(kind) { - return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + return !!(ts.modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */); } ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ @@ -13825,7 +13860,9 @@ var ts; } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { @@ -14078,7 +14115,9 @@ var ts; if (node.kind === 338 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ false, isInJSDoc(node)); } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -15513,6 +15552,10 @@ var ts; return node.kind === 177 /* TypeQuery */; } ts.isPartOfTypeQuery = isPartOfTypeQuery; + function isNamespaceReexportDeclaration(node) { + return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 273 /* ExternalModuleReference */; } @@ -16125,6 +16168,7 @@ var ts; parent.kind === 267 /* ExportAssignment */ || parent.kind === 164 /* PropertyDeclaration */ || parent.kind === 234 /* ExpressionStatement */ && node.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 243 /* ReturnStatement */ || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) { return parent; @@ -19325,6 +19369,10 @@ var ts; return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; + function getUseDefineForClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === 99 /* ESNext */ : compilerOptions.useDefineForClassFields; + } + ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return oldOptions !== newOptions && ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); @@ -19396,19 +19444,33 @@ var ts; } (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); } - } + }, + setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { + this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); + var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var cache = createSymlinkCache(cwd, getCanonicalFileName); - var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { - return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + var symlinks = ts.flatMap(files, function (sf) { + var pairs = sf.resolvedModules && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedModules.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) ? [res.resolvedFileName, res.originalPath] : undefined; + })); + return ts.concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] : undefined; }))); - })); + }); for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); @@ -20405,7 +20467,11 @@ var ts; var ts; (function (ts) { function createParenthesizerRules(factory) { + var binaryLeftOperandParenthesizerCache; + var binaryRightOperandParenthesizerCache; return { + getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName, @@ -20426,6 +20492,24 @@ var ts; parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType, parenthesizeTypeArguments: parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); }; + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); }; + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } /** * Determines whether the operand to a BinaryExpression needs to be parenthesized. * @@ -20754,6 +20838,8 @@ var ts; } ts.createParenthesizerRules = createParenthesizerRules; ts.nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; }, + getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; }, parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; }, parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; }, parenthesizeExpressionOfComputedPropertyName: ts.identity, @@ -21695,6 +21781,7 @@ var ts; case 155 /* BigIntKeyword */: case 141 /* NeverKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 147 /* StringKeyword */: case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: @@ -21777,15 +21864,15 @@ var ts; if (flags & 32 /* Static */) { result.push(createModifier(123 /* StaticKeyword */)); } + if (flags & 16384 /* Override */) { + result.push(createModifier(156 /* OverrideKeyword */)); + } if (flags & 64 /* Readonly */) { result.push(createModifier(142 /* ReadonlyKeyword */)); } if (flags & 256 /* Async */) { result.push(createModifier(129 /* AsyncKeyword */)); } - if (flags & 16384 /* Override */) { - result.push(createModifier(156 /* OverrideKeyword */)); - } return result; } // @@ -21857,7 +21944,7 @@ var ts; propagateChildFlags(node.questionToken); if (questionToken) node.transformFlags |= 1 /* ContainsTypeScript */; - if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */) + if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */) node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) node.transformFlags |= 512 /* ContainsES2015 */; @@ -22524,7 +22611,7 @@ var ts; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { var node = createBaseBindingLikeDeclaration(199 /* BindingElement */, /*decorators*/ undefined, - /*modifiers*/ undefined, name, initializer); + /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= @@ -29360,6 +29447,7 @@ var ts; case 324 /* JSDocPrivateTag */: case 325 /* JSDocProtectedTag */: case 326 /* JSDocReadonlyTag */: + case 321 /* JSDocDeprecatedTag */: return visitNode(cbNode, node.tagName) || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); case 340 /* PartiallyEmittedExpression */: @@ -31450,19 +31538,21 @@ var ts; function parseParameterWorker(inOuterAwaitContext) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); + // 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(); if (token() === 107 /* ThisKeyword */) { - var node_1 = factory.createParameterDeclaration( - /*decorators*/ undefined, + var node_1 = factory.createParameterDeclaration(decorators, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); + if (decorators) { + parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } return withJSDoc(finishNode(node_1, pos), hasJSDoc); } - // 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 savedTopLevel = topLevel; topLevel = false; var modifiers = parseModifiers(); @@ -33748,12 +33838,13 @@ var ts; // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var openBracePosition = scanner.getTokenPos(); if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { var multiLine = scanner.hasPrecedingLineBreak(); var statements = parseList(1 /* BlockStatements */, parseStatement); parseExpectedMatchingBrackets(18 /* OpenBraceToken */, 19 /* CloseBraceToken */, openBracePosition); - var result = finishNode(factory.createBlock(statements, multiLine), pos); + var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); if (token() === 62 /* EqualsToken */) { parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); nextToken(); @@ -33762,7 +33853,7 @@ var ts; } else { var statements = createMissingList(); - return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -33789,11 +33880,13 @@ var ts; } function parseEmptyStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(26 /* SemicolonToken */); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(98 /* IfKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); @@ -33801,10 +33894,11 @@ var ts; parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var thenStatement = parseStatement(); var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(89 /* DoKeyword */); var statement = parseStatement(); parseExpected(114 /* WhileKeyword */); @@ -33817,20 +33911,22 @@ var ts; // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. parseOptional(26 /* SemicolonToken */); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(114 /* WhileKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(96 /* ForKeyword */); var awaitToken = parseOptionalToken(130 /* AwaitKeyword */); parseExpected(20 /* OpenParenToken */); @@ -33866,34 +33962,37 @@ var ts; parseExpected(21 /* CloseParenToken */); node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(kind === 242 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); var node = kind === 242 /* BreakStatement */ ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(104 /* ReturnKeyword */); var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(115 /* WithKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { var pos = getNodePos(); @@ -33922,17 +34021,19 @@ var ts; } function parseSwitchStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(106 /* SwitchKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { // ThrowStatement[Yield] : // throw [no LineTerminator here]Expression[In, ?Yield]; var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(108 /* ThrowKeyword */); // Because of automatic semicolon insertion, we need to report error if this // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' @@ -33945,11 +34046,12 @@ var ts; expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } // TODO: Review for error recovery function parseTryStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(110 /* TryKeyword */); var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -33960,7 +34062,7 @@ var ts; parseExpected(95 /* FinallyKeyword */); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { var pos = getNodePos(); @@ -33979,9 +34081,10 @@ var ts; } function parseDebuggerStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(86 /* DebuggerKeyword */); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement() { // Avoiding having to do the lookahead for a labeled statement by just trying to parse @@ -35368,7 +35471,6 @@ var ts; state = 2 /* SavingComments */; var commentEnd = scanner.getStartPos(); var linkStart = scanner.getTextPos() - 1; - // TODO: redo here var link = parseJSDocLink(linkStart); if (link) { if (!linkEnd) { @@ -35570,8 +35672,9 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */ || !previousWhitespace && state === 2 /* SavingComments */) { - // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace + if (state === 3 /* SavingBackticks */ + || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace comments.push(scanner.getTokenText()); break; } @@ -35648,6 +35751,10 @@ var ts; return comments.join(""); } } + function isNextJSDocTokenWhitespace() { + var next = nextTokenJSDoc(); + return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */; + } function parseJSDocLink(start) { if (!tryParse(parseJSDocLinkPrefix)) { return undefined; @@ -37151,8 +37258,8 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - /* @internal */ - ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsWithoutBuild = [ + // CommandLine only options { name: "all", type: "boolean", @@ -37938,7 +38045,9 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins }, - ]); + ]; + /* @internal */ + ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsWithoutBuild); /* @internal */ ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); /* @internal */ @@ -37953,8 +38062,7 @@ var ts; ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) { return ts.hasProperty(option, "transpileOptionValue"); }); - /* @internal */ - ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsOnlyBuild = [ { name: "verbose", shortName: "v", @@ -37982,7 +38090,9 @@ var ts; description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean" } - ]); + ]; + /* @internal */ + ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsOnlyBuild); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -38036,6 +38146,10 @@ var ts; return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations)); } ts.getOptionsNameMap = getOptionsNameMap; + var compilerOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; /* @internal */ ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, @@ -38097,6 +38211,10 @@ var ts; return option.name; } function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { + var _a; + if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -38251,6 +38369,7 @@ var ts; } /*@internal*/ ts.compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -38283,7 +38402,12 @@ var ts; function getBuildOptionsNameMap() { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts)); } + var buildOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap: getOptionsNameMap + }; var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: ts.buildOpts, unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, @@ -40034,13 +40158,24 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) { var traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined; + var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -40063,6 +40198,8 @@ var ts; trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); } } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -40073,17 +40210,31 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary: primary, + resolvedFileName: resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId: packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, result); + if (traceEnabled) + traceResult(result); + return result; + function traceResult(result) { + var _a; + if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { // Check primary library paths if (typeRoots && typeRoots.length) { @@ -40113,20 +40264,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = void 0; + var result_4; if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); - result = searchResult && searchResult.value; + result_4 = searchResult && searchResult.value; } else { var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; - result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); } - var resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - return resolvedFile; + return resolvedTypeScriptOnly(result_4); } else { if (traceEnabled) { @@ -40181,22 +40328,21 @@ var ts; return result; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName); - } - ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ function createCacheWithRedirects(options) { var ownMap = new ts.Map(); var redirectsMap = new ts.Map(); return { - ownMap: ownMap, + getOwnMap: getOwnMap, redirectsMap: redirectsMap, getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, clear: clear, setOwnOptions: setOwnOptions, setOwnMap: setOwnMap }; + function getOwnMap() { + return ownMap; + } function setOwnOptions(newOptions) { options = newOptions; } @@ -40222,26 +40368,88 @@ var ts; } } ts.createCacheWithRedirects = createCacheWithRedirects; - /*@internal*/ - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap }; + function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + var cache; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear }; + function getPackageJsonInfo(packageJsonPath) { + return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + if (!options.configFile) + return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + // The own map will be for projectCompilerOptions + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + // Set correct own map + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + var ref = { + sourceFile: options.configFile, + commandLine: { options: options } + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options); + } + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) { + return { + getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, + clear: clear, + update: update, + }; + function clear() { + directoryToModuleNameMap.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap); + } function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); }); } + } + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + var preDirectoryResolutionCache = 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; } }); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + packageJsonInfoCache.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); + } function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } - function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { - var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - var result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; - } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); return { get: get, set: set }; @@ -40308,7 +40516,17 @@ var ts; } } } - ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + ts.createModuleResolutionCache = createModuleResolutionCache; + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache.clear(); + } + } + ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache) { var containingDirectory = ts.getDirectoryPath(containingFile); var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -40586,7 +40804,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; 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, state.resultFromCache); function tryResolve(extensions) { @@ -40646,7 +40864,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -40679,8 +40897,9 @@ var ts; * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo" * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo" */ + /* @internal */ function parseNodeModuleFromPath(resolved) { - var path = ts.normalizePath(resolved.path); + var path = ts.normalizePath(resolved); var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; @@ -40692,6 +40911,7 @@ var ts; } return path.slice(0, indexAfterPackageName); } + ts.parseNodeModuleFromPath = parseNodeModuleFromPath; function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; @@ -40775,21 +40995,43 @@ var ts; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c; var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) + trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) + trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + var directoryExists = ts.directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = ts.readJson(packageJsonPath, host); if (traceEnabled) { trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists); // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results state.failedLookupLocations.push(packageJsonPath); } @@ -41038,7 +41280,7 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath @@ -41079,13 +41321,13 @@ var ts; * This is the minumum code needed to expose that functionality; the rest is in the host. */ /* @internal */ - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { 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 state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache); } @@ -41731,6 +41973,7 @@ var ts; } if (node.kind === 298 /* SourceFile */) { node.flags |= emitFlags; + node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -43048,9 +43291,9 @@ var ts; var saveCurrentFlow = currentFlow; for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { var typeAlias = delayedTypeAliases_1[_i]; - var host = ts.getJSDocHost(typeAlias); - container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); })) || file; - blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file; + var host = typeAlias.parent.parent; + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -43636,8 +43879,8 @@ var ts; } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + // Incorrect export assignment in some sort of block construct + bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node)); } else { var flags = ts.exportAssignmentIsAlias(node) @@ -44815,6 +45058,7 @@ var ts; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -44823,7 +45067,7 @@ var ts; var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384 /* FreshLiteral */; var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); @@ -45010,6 +45254,7 @@ var ts; return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, + getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, argumentCount) { return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */); @@ -45181,14 +45426,14 @@ var ts; var autoType = createIntrinsicType(1 /* Any */, "any"); var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); - var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */); + var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 131072 /* ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -45214,7 +45459,7 @@ var ts; var voidType = createIntrinsicType(16384 /* Void */, "void"); var neverType = createIntrinsicType(131072 /* Never */, "never"); var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -45226,7 +45471,7 @@ var ts; var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -45235,7 +45480,7 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */; + anyFunctionType.objectFlags |= 524288 /* NonInferrableType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -45897,7 +46142,7 @@ var ts; } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property - return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -45925,7 +46170,7 @@ var ts; return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); @@ -46060,7 +46305,7 @@ var ts; case 164 /* PropertyDeclaration */: // static properties in classes introduce temporary variables if (ts.hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + return target < 99 /* ESNext */ || !useDefineForClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -46445,7 +46690,7 @@ var ts; } // Perform extra checks only if error reporting was requested if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* 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. @@ -46776,8 +47021,7 @@ var ts; } } function getDeclarationOfAliasSymbol(symbol) { - var _a; - return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(isAliasSymbolDeclaration); + return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration); } /** * An alias symbol is created by one of the following declarations: @@ -46792,6 +47036,7 @@ var ts; * module.exports = * {} * {name: } + * const { x } = require ... */ function isAliasSymbolDeclaration(node) { return node.kind === 261 /* ImportEqualsDeclaration */ @@ -47022,7 +47267,7 @@ var ts; return undefined; } var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -48098,7 +48343,7 @@ var ts; var _loop_8 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } } @@ -48113,7 +48358,7 @@ var ts; // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred // to one another anyway) - if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) { + if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } break; @@ -48145,7 +48390,7 @@ var ts; if (typeof state_2 === "object") return state_2.value; } - return callback(globals); + return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace @@ -48165,11 +48410,11 @@ var ts; /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) */ - function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols, ignoreQualification); + var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables.pop(); return result; } @@ -48187,7 +48432,7 @@ var ts; !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols, ignoreQualification) { + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { // If symbol is directly available by its name in the symbol table if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; @@ -48200,6 +48445,8 @@ var ts; && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // If we're looking up a local name to reference directly, omit namespace reexports, otherwise when we're trawling through an export list to make a dotted name, we can keep it + && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */))) { @@ -48302,7 +48549,7 @@ var ts; return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -48563,7 +48810,7 @@ var ts; return flags & 814775659 /* NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { - return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */)); + return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* Object */) && !!(ts.getObjectFlags(type) & 16777216 /* IsClassInstanceClone */))); } function createNodeBuilder() { return { @@ -49176,7 +49423,7 @@ var ts; } if (resolvedType.stringIndexInfo) { var indexSignature = void 0; - if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + if (resolvedType.objectFlags & 1024 /* ReverseMapped */) { indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context)); } else { @@ -49220,10 +49467,23 @@ var ts; } return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + // Use placeholders for reverse mapped types we've either already descended into, or which + // are nested reverse mappings within a mapping over a non-anonymous type. The later is a restriction mostly just to + // reduce the blowup in printback size from doing, eg, a deep reverse mapping over `Window`. + // Since anonymous types usually come from expressions, this allows us to preserve the output + // for deep mappings which likely come from expressions, while truncating those parts which + // come from mappings over library functions. + return !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) + && (ts.contains(context.reverseMappedStack, propertySymbol) + || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0]) + && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16 /* Anonymous */))); + } function addPropertyToElementList(propertySymbol, context, typeElements) { var _a; var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */); - var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; @@ -49255,16 +49515,20 @@ var ts; } } else { - var savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; var propertyTypeNode = void 0; - if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } } - context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; @@ -49305,25 +49569,25 @@ var ts; var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); /** Map from type reference identifier text to [type, index in `result` where the type node is] */ var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; - var result_4 = []; + var result_5 = []; var i = 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result_4.push(typeNode_1); + result_5.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result_4.push(typeNode); + result_5.push(typeNode); if (seenNames && ts.isIdentifierTypeReference(typeNode)) { - seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]); + seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]); } } } @@ -49345,13 +49609,13 @@ var ts; })) { for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var _a = types_3[_i], type = _a[0], resultIndex = _a[1]; - result_4[resultIndex] = typeToTypeNodeHelper(type, context); + result_5[resultIndex] = typeToTypeNodeHelper(type, context); } } }); context.flags = saveContextFlags; } - return result_4; + return result_5; } } function typesAreSameReference(a, b) { @@ -49685,7 +49949,7 @@ var ts; // specifier preference var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map()); links.specifierCache.set(contextFile.path, specifier); } @@ -49975,13 +50239,13 @@ var ts; function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { if (type !== errorType && enclosingDeclaration) { var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) { // try to reuse the existing annotation var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); - if (result_5) { - return result_5; + var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_6) { + return result_6; } } } @@ -49998,10 +50262,14 @@ var ts; function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { if (type !== errorType && context.enclosingDeclaration) { var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); - if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) { + var annotated = getTypeFromTypeNode(annotation); + var thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -51755,7 +52023,7 @@ var ts; var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= 131072 /* ObjectRestType */; + result.objectFlags |= 8388608 /* ObjectRestType */; return result; } function isGenericTypeWithUndefinedConstraint(type) { @@ -52063,6 +52331,22 @@ var ts; } ; } + /** Create a synthetic property access flow node after the last statement of the file */ + function getFlowTypeFromCommonJSExport(symbol) { + var file = ts.getSourceFileOfNode(symbol.declarations[0]); + var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName); + var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); }); + var reference = areAllModuleExports + ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName) + : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + ts.setParent(reference.expression.expression, reference.expression); + } + ts.setParent(reference.expression, reference); + ts.setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); + } function getFlowTypeInConstructor(symbol, constructor) { var accessName = ts.startsWith(symbol.escapedName, "__#") ? ts.factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) @@ -52178,7 +52462,7 @@ var ts; mergeSymbolTable(exports, s.exports); } var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - type.objectFlags |= 16384 /* JSLiteral */; + type.objectFlags |= 8192 /* JSLiteral */; return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { @@ -52279,9 +52563,9 @@ 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.stringIndexInfo, exportedType.numberIndexInfo); - result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + result.objectFlags |= (ts.getObjectFlags(type) & 8192 /* JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { - result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type + result.objectFlags |= 16777216 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type } return result; } @@ -52340,7 +52624,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -52364,7 +52648,7 @@ var ts; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -52383,7 +52667,7 @@ var ts; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -52640,38 +52924,31 @@ var ts; if (writing === void 0) { writing = false; } var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); // For write operations, prioritize type annotations on the setter - if (writing) { - var setterParameterType_1 = getAnnotatedAccessorType(setter); - if (setterParameterType_1) { - var flags = ts.getCheckFlags(symbol); - if (flags & 1 /* Instantiated */) { - var links = getSymbolLinks(symbol); - return instantiateType(setterParameterType_1, links.mapper); - } - return setterParameterType_1; - } + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); } // Else defer to the getter type if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } // Try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + var getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + if (setterType) { + return setterType; } // If there are no specified types, try to infer it from the body of the get accessor if it exists. if (getter && getter.body) { - return getReturnTypeFromBody(getter); + var returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); } // Otherwise, fall back to 'any'. if (setter) { @@ -52688,6 +52965,13 @@ var ts; return anyType; } return undefined; + function instantiateTypeIfNeeded(type, symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); + } + return type; + } } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); @@ -52752,14 +53036,16 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); + var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontResolveAlias*/ true); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 111551 /* Value */ - ? getTypeOfSymbol(targetSymbol) - : errorType; + links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -54363,6 +54649,12 @@ var ts; } } } + function replaceIndexedAccess(instantiable, type, replacement) { + // map type.indexType to 0 + // map type.objectType to `[TReplacement]` + // thus making the indexed access `[TReplacement][0]` or `TReplacement` + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } function getIndexInfoOfIndexSymbol(indexSymbol, indexKind) { var declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); if (!declaration) @@ -54383,8 +54675,21 @@ var ts; inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ + && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ + && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) { + // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is + // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of + // type identities produced, we simplify such indexed access occurences + var newTypeParam = type.constraintType.type.objectType; + var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.mappedType = newMappedType; + inferredProp.constraintType = getIndexType(newTypeParam); + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -54598,7 +54903,7 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 2048 /* ReverseMapped */) { + else if (type.objectFlags & 1024 /* ReverseMapped */) { resolveReverseMappedTypeMembers(type); } else if (type.objectFlags & 16 /* Anonymous */) { @@ -55017,6 +55322,7 @@ var ts; return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b; var singleProp; var propSet; var indexTypes; @@ -55025,8 +55331,9 @@ var ts; var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var current = _a[_i]; + var mergedInstantiations = false; + for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) { + var current = _c[_i]; var type = getApparentType(current); if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); @@ -55042,13 +55349,25 @@ var ts; singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new ts.Map(); - propSet.set(getSymbolId(singleProp), singleProp); + var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + // If the symbols are instances of one another with identical types - consider the symbols + // equivalent and just use the first one, which thus allows us to avoid eliding private + // members when intersecting a (this-)instantiations of a class with it's raw base or another instance + if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 /* True */ : 0 /* False */; }) === -1 /* True */) { + // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used + // to do when we recorded multiple distinct symbols so that we still get, eg, `Array.length` printed + // back and not `Array.length` when we're looking at a `.length` access on a `string[] | number[]` + mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - var id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new ts.Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + var id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | @@ -55066,7 +55385,7 @@ var ts; checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0); indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304 /* ContainsSpread */)) { checkFlags |= 32 /* WritePartial */; indexTypes = ts.append(indexTypes, undefinedType); } @@ -55082,7 +55401,19 @@ var ts; return undefined; } if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + // No symbol from a union/intersection should have a `.parent` set (since unions/intersections don't act as symbol parents) + // Unless that parent is "reconstituted" from the "first value declaration" on the symbol (which is likely different than its instantiated parent!) + // They also have a `.containingType` set, which affects some services endpoints behavior, like `getRootSymbol` + var clone_1 = createSymbolWithType(singleProp, singleProp.type); + clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent; + clone_1.containingType = containingType; + clone_1.mapper = singleProp.mapper; + return clone_1; + } + else { + return singleProp; + } } var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; @@ -55091,8 +55422,8 @@ var ts; var propTypes = []; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; - for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { - var prop = props_1[_b]; + for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { + var prop = props_1[_d]; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } @@ -55169,15 +55500,15 @@ var ts; * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. */ function getReducedType(type) { - if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 67108864 /* ContainsIntersections */) { return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); } else if (type.flags & 2097152 /* Intersection */) { - if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { - type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); + if (!(type.objectFlags & 67108864 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 67108864 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 134217728 /* IsNeverIntersection */ : 0); } - return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + return type.objectFlags & 134217728 /* IsNeverIntersection */ ? neverType : type; } return type; } @@ -55207,7 +55538,7 @@ var ts; return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); } function elaborateNeverIntersection(errorInfo, type) { - if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + if (type.flags & 2097152 /* Intersection */ && ts.getObjectFlags(type) & 134217728 /* IsNeverIntersection */) { var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); @@ -55364,6 +55695,9 @@ var ts; } return false; } + function isOptionalPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && node.questionToken; + } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; @@ -55518,8 +55852,7 @@ var ts; if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) return undefined; var typeTag = ts.getJSDocTypeTag(node); - var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); @@ -55884,6 +56217,17 @@ var ts; else if (grandParent.kind === 160 /* TypeParameter */ && grandParent.parent.kind === 191 /* MappedType */) { inferences = ts.append(inferences, keyofConstraintType); } + // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends + // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template + // of the check type's mapped type + else if (grandParent.kind === 191 /* MappedType */ && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 185 /* ConditionalType */ && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 191 /* MappedType */ && + grandParent.parent.checkType.type) { + var checkMappedType_1 = grandParent.parent.checkType; + var nodeType = getTypeFromTypeNode(checkMappedType_1.type); + inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); + } } } } @@ -55957,7 +56301,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 3670016 /* PropagatingFlags */; + return result & 917504 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -56086,11 +56430,21 @@ var ts; ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } + // We refrain from associating a local type alias with an instantiation of a top-level type alias + // because the local alias may end up being referenced in an inferred return type where it is not + // accessible--which in turn may lead to a large structural expansion of the type when generating + // a .d.ts file. See #43622 for an example. var aliasSymbol = getAliasSymbolForTypeNode(node); - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol) { + var _a; + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias); + return !!(declaration && ts.getContainingFunction(declaration)); + } function getTypeReferenceName(node) { switch (node.kind) { case 174 /* TypeReference */: @@ -56186,9 +56540,17 @@ var ts; } function getConditionalFlowTypeOfType(type, node) { var constraints; + var covariant = true; while (node && !ts.isStatement(node) && node.kind !== 312 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { + // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but + // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax + if (parent.kind === 161 /* Parameter */) { + covariant = !covariant; + } + // Always substitute on type parameters, regardless of variance, since even + // in contravariant positions, they may rely on substituted constraints to be valid + if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -56780,7 +57142,7 @@ var ts; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; } else { @@ -56982,8 +57344,8 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | - (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 67108864 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } function getUnionOrIntersectionTypePredicate(signatures, kind) { @@ -57041,7 +57403,7 @@ var ts; var typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id; + "#" + origin.type.id + "|" + getTypeListId(types); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { @@ -57168,7 +57530,7 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -57177,7 +57539,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -57206,7 +57568,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -57604,7 +57966,7 @@ var ts; if (noImplicitAny) { return false; // Flag is meaningless under `noImplicitAny` mode } - if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + if (ts.getObjectFlags(type) & 8192 /* JSLiteral */) { return true; } if (type.flags & 1048576 /* Union */) { @@ -57818,6 +58180,13 @@ var ts; } return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) { + type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ | + (isGenericObjectType(type.substitute) || isGenericObjectType(type.baseType) ? 8388608 /* IsGenericObjectType */ : 0); + } + return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); + } return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type) { @@ -57828,6 +58197,13 @@ var ts; } return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) { + type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ | + (isGenericIndexType(type.substitute) || isGenericIndexType(type.baseType) ? 33554432 /* IsGenericIndexType */ : 0); + } + return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); + } return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type); } function isThisTypeParameter(type) { @@ -58085,7 +58461,7 @@ var ts; // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { var isUnwrapped = isTypicalNondistributiveConditional(root); - var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { @@ -58098,7 +58474,7 @@ var ts; // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); } // It's possible for 'infer T' type paramteters to be given uninstantiated constraints when the // those type parameters are used in type references (see getInferredTypeParameterConstraint). For @@ -58355,7 +58731,7 @@ var ts; } } var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return spread; } } @@ -58461,7 +58837,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */ | 4194304 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ @@ -58881,8 +59257,9 @@ var ts; outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || ts.emptyArray; - typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? - ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) : + var allDeclarations_1 = type.objectFlags & 4 /* Reference */ ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) : typeParameters; links.outerTypeParameters = typeParameters; } @@ -58927,7 +59304,7 @@ var ts; return true; } } - return !!ts.forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node) { @@ -58939,6 +59316,9 @@ var ts; getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality case 177 /* TypeQuery */: return true; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + return (!node.type && !!node.body) || !!ts.forEachChild(node, containsReference); } return !!ts.forEachChild(node, containsReference); } @@ -59118,6 +59498,9 @@ var ts; var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; } + if (objectFlags & 1024 /* ReverseMapped */) { + return instantiateReverseMappedType(type, mapper); + } return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; @@ -59167,6 +59550,21 @@ var ts; } return type; } + function instantiateReverseMappedType(type, mapper) { + var innerMappedType = instantiateType(type.mappedType, mapper); + if (!(ts.getObjectFlags(innerMappedType) & 32 /* Mapped */)) { + return type; + } + var innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304 /* Index */)) { + return type; + } + var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); + if (instantiated) { + return instantiated; + } + return type; // Nested invocation of `inferTypeForHomomorphicMappedType` or the `source` instantiated into something unmappable + } function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -60082,7 +60480,7 @@ var ts; return false; } function isIgnoredJsxProperty(source, sourceProp) { - return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); + return ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { while (true) { @@ -60092,6 +60490,7 @@ var ts; type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; @@ -60409,7 +60808,7 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1 /* True */; } - reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */)); return 0 /* False */; } // Normalize the source and target types: Turn fresh literal types into regular literal types, @@ -60452,8 +60851,8 @@ var ts; if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); + var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -60538,7 +60937,7 @@ var ts; // We suppress recursive intersection property checks because they can generate lots of work when relating // recursive intersections that are structurally similar but not exactly identical. See #37854. if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); inPropertyCheck = false; @@ -60547,8 +60946,10 @@ var ts; return result; function reportErrorResults(source, target, result, isComparingJsxAttributes) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; var maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -60595,7 +60996,7 @@ var ts; if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { var sourceUnionOrIntersection = source; var targetUnionOrIntersection = target; - if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144 /* PrimitiveUnion */) { + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536 /* PrimitiveUnion */) { // There's a fast path for comparing primitive unions return; } @@ -60620,11 +61021,11 @@ var ts; } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & 3145728 /* UnionOrIntersection */) { - var result_6 = eachTypeRelatedToSomeType(source, target); - if (result_6) { - result_6 &= eachTypeRelatedToSomeType(target, source); + var result_7 = eachTypeRelatedToSomeType(source, target); + if (result_7) { + result_7 &= eachTypeRelatedToSomeType(target, source); } - return result_6; + return result_7; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -60639,10 +61040,10 @@ var ts; } function hasExcessProperties(source, target, reportErrors) { var _a; - if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; @@ -61056,21 +61457,21 @@ var ts; if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_7 = 0 /* False */; + var result_8 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_8; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_8; } } } @@ -61150,6 +61551,20 @@ var ts; } } else if (target.flags & 8388608 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { + // Relate components directly before falling back to constraint relationships + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } // A type S is related to a type T[K] if S is related to C, where C is the base // constraint of T[K] for writing. if (relation === assignableRelation || relation === comparableRelation) { @@ -61160,11 +61575,24 @@ var ts; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0); var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + // create a new chain for the constraint error + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { // A source type T is related to a target type { [P in X]: T[P] } @@ -61242,23 +61670,14 @@ var ts; // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - var result_8 = inferTypesFromTemplateLiteralType(source, target); - if (result_8 && ts.every(result_8, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + var result_9 = inferTypesFromTemplateLiteralType(source, target); + if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { return -1 /* True */; } } if (source.flags & 8650752 /* TypeVariable */) { - if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { - // A type S[K] is related to a type T[J] if S is related to T and K is related to J. - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - result &= isRelatedTo(source.indexType, target.indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - else { + // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch + if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) { var constraint = getConstraintOfType(source); if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. @@ -61273,7 +61692,7 @@ var ts; 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, reportErrors, /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -61285,6 +61704,16 @@ var ts; return result; } } + else if (source.flags & 134217728 /* TemplateLiteral */) { + if (!(target.flags & 134217728 /* TemplateLiteral */)) { + var baseConstraint = getBaseConstraintOfType(source); + var constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; + } + } + } else if (source.flags & 268435456 /* StringMapping */) { if (target.flags & 268435456 /* StringMapping */ && source.symbol === target.symbol) { if (result = isRelatedTo(source.type, target.type, reportErrors)) { @@ -61311,7 +61740,7 @@ var ts; if (sourceParams) { // If the source has infer type parameters, we instantiate them in the context of the target var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } @@ -61369,7 +61798,7 @@ var ts; return 0 /* False */; } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && - !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + !(ts.getObjectFlags(source) & 4096 /* MarkerType */ || ts.getObjectFlags(target) & 4096 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. @@ -61397,7 +61826,7 @@ var ts; } // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})` // and not `{} <- fresh({}) <- {[idx: string]: any}` - else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) { + else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 /* FreshLiteral */ && !isEmptyObjectType(source)) { return 0 /* False */; } // Even if relationship doesn't hold for unions, intersections, or generic type references, @@ -61435,14 +61864,19 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_9) { - return result_9; + var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_10) { + return result_10; } } } } return 0 /* False */; + function countMessageChainBreadth(info) { + if (!info) + return 0; + return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0); + } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -61504,13 +61938,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_10; + var result_11; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } } @@ -61650,7 +62084,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_11 = unionParent ? 0 /* False */ : -1 /* True */; + var result_12 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -61660,7 +62094,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_11 &= related; + result_12 &= related; } else { if (related) { @@ -61668,17 +62102,17 @@ var ts; } } } - if (unionParent && !result_11 && targetIsOptional) { - result_11 = isRelatedTo(source, undefinedType); + if (unionParent && !result_12 && targetIsOptional) { + result_12 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_11 && reportErrors) { + if (unionParent && !result_12 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_11; + return result_12; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); @@ -62280,7 +62714,7 @@ var ts; // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); - result.objectFlags |= 8192 /* MarkerType */; + result.objectFlags |= 4096 /* MarkerType */; return result; } function getAliasVariances(symbol) { @@ -62454,8 +62888,8 @@ var ts; } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. - function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons @@ -62473,23 +62907,26 @@ var ts; function isDeeplyNestedType(type, stack, depth) { if (depth >= 5) { var identity_1 = getRecursionIdentity(type); - if (identity_1) { - var count = 0; - for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= 5) { - return true; - } + var count = 0; + for (var i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity_1) { + count++; + if (count >= 5) { + return true; } } } } return false; } - // Types with constituents that could circularly reference the type have a recursion identity. The recursion - // identity is some object that is common to instantiations of the type with the same origin. + // The recursion identity of a type is an object identity that is shared among multiple instantiations of the type. + // We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with + // the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all + // instantiations of that type have the same recursion identity. The default recursion identity is the object + // identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly + // reference the type have a recursion identity that differs from the object identity. function getRecursionIdentity(type) { + // Object and array literals are known not to contain recursive references and don't need a recursion identity. if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) { // Deferred type references are tracked through their associated AST node. This gives us finer @@ -62507,6 +62944,9 @@ var ts; return type.target; } } + if (type.flags & 262144 /* TypeParameter */) { + return type.symbol; + } if (type.flags & 8388608 /* IndexedAccess */) { // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A do { @@ -62518,7 +62958,7 @@ var ts; // The root object represents the origin of the conditional type return type.root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; @@ -62656,6 +63096,9 @@ var ts; // 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; }); @@ -62688,12 +63131,30 @@ var ts; function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return isArrayType(type) || hasArrayOrReadonlyArrayBaseType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } - function hasArrayOrReadonlyArrayBaseType(type) { - return !!(ts.getObjectFlags(type) & 4 /* Reference */) - && !!(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */) - && ts.some(getBaseTypes(type.target), isArrayType); + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */)) { + return undefined; + } + if (ts.getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) { + return ts.getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : undefined; + } + type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */; + var target = type.target; + var bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; // If the interface has any members, they may subtype members in the base, so we should do a full structural comparison + } + var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type))); + } + type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */; + return type.cachedEquivalentBaseType = instantiatedBase; } function isEmptyArrayLiteralType(type) { var elementType = getElementTypeOfArrayType(type); @@ -62938,7 +63399,7 @@ var ts; function isObjectTypeWithInferableIndex(type) { return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */); @@ -62971,7 +63432,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -62982,7 +63443,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */; + regularNew.objectFlags |= resolved.objectFlags & ~16384 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -63012,7 +63473,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; - if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304 /* ContainsSpread */)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; names.set(prop.escapedName, prop); @@ -63061,14 +63522,14 @@ var ts; var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (8192 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -63113,7 +63574,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -63139,7 +63600,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -63219,7 +63680,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -63335,16 +63796,16 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) { - return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); + if (objectFlags & 1048576 /* CouldContainTypeVariablesComputed */) { + return !!(objectFlags & 2097152 /* CouldContainTypeVariables */); } var result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 8388608 /* ObjectRestType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { - type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); + type.objectFlags |= 1048576 /* CouldContainTypeVariablesComputed */ | (result ? 2097152 /* CouldContainTypeVariables */ : 0); } return result; } @@ -63404,7 +63865,7 @@ var ts; // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive // arrow function, but is considered partially inferable because property 'a' has an inferable type. function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 524288 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) || isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType); } @@ -63428,14 +63889,18 @@ var ts; } // For all other object types we infer a new object type where the reverse mapping has been // applied to the type of each property. - var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + var reversed = createObjectType(1024 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType, target, constraint) { var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); @@ -63633,7 +64098,7 @@ var ts; if (contravariant === void 0) { contravariant = false; } var bivariant = false; var propagationType; - var inferencePriority = 1024 /* MaxValue */; + var inferencePriority = 2048 /* MaxValue */; var allowComplexConstraintInference = true; var visited; var sourceStack; @@ -63720,8 +64185,8 @@ var ts; // 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 (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || - (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || + (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -63748,7 +64213,7 @@ var ts; clearCachedInferences(inferences); } } - if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -63788,7 +64253,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - inferWithPriority(empty, target.type, 128 /* LiteralKeyof */); + inferWithPriority(empty, target.type, 256 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -63800,6 +64265,13 @@ var ts; inferFromTypes(source.type, target.type); } } + else if (source.flags & 33554432 /* Substitution */) { + inferFromTypes(source.baseType, target); + var oldPriority = priority; + priority |= 4 /* SubstituteSource */; + inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority + priority = oldPriority; + } else if (target.flags & 16777216 /* Conditional */) { invokeOnce(source, target, inferToConditionalType); } @@ -63819,7 +64291,7 @@ var ts; } else { source = getReducedType(source); - if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { + if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` @@ -63857,26 +64329,22 @@ var ts; } (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */); var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; // We stop inferring and report a circularity if we encounter duplicate recursion identities on both // the source side and the target side. var saveExpandingFlags = expandingFlags; - var sourceIdentity = getRecursionIdentity(source) || source; - var targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && ts.contains(sourceStack, sourceIdentity)) + var sourceIdentity = getRecursionIdentity(source); + var targetIdentity = getRecursionIdentity(target); + if (ts.contains(sourceStack, sourceIdentity)) expandingFlags |= 1 /* Source */; - if (targetIdentity && ts.contains(targetStack, targetIdentity)) + if (ts.contains(targetStack, targetIdentity)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { - if (sourceIdentity) - (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) - (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) - targetStack.pop(); - if (sourceIdentity) - sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = -1 /* Circularity */; @@ -63916,7 +64384,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -63968,7 +64436,7 @@ var ts; else { for (var i = 0; i < sources.length; i++) { var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; inferFromTypes(sources[i], t); if (inferencePriority === priority) matched_1[i] = true; @@ -64047,7 +64515,7 @@ var ts; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? 8 /* PartialHomomorphicMappedType */ : 4 /* HomomorphicMappedType */); + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 /* NonInferrableType */ ? 16 /* PartialHomomorphicMappedType */ : 8 /* HomomorphicMappedType */); } } return true; @@ -64055,7 +64523,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */); + inferWithPriority(getIndexType(source), constraintType, 32 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -64084,7 +64552,7 @@ var ts; } else { var savePriority = priority; - priority |= contravariant ? 32 /* ContravariantConditional */ : 0; + priority |= contravariant ? 64 /* ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, target.flags); priority = savePriority; @@ -64207,7 +64675,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -64258,7 +64726,7 @@ var ts; return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); } function isObjectOrArrayLiteralType(type) { - return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */)); + return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 32768 /* ArrayLiteral */)); } function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { @@ -64271,7 +64739,7 @@ var ts; return candidates; } function getContravariantInference(inference) { - return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } function getCovariantInference(inference, signature) { // Extract all object and array literal types and replace them with a single widened and normalized type. @@ -64288,7 +64756,7 @@ var ts; candidates; // If all inferences were made from a position that implies a combined result, infer a union type. // Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ? + var unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -64585,14 +65053,14 @@ var ts; function getKeyPropertyName(unionType) { var types = unionType.types; // We only construct maps for large unions with non-primitive constituents. - if (types.length < 10 || ts.getObjectFlags(unionType) & 262144 /* PrimitiveUnion */) { + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { return undefined; } if (unionType.keyPropertyName === undefined) { // The candidate key property name is the name of the first property with a unit type in one of the // constituent types. var keyPropertyName = ts.forEach(types, function (t) { - return t.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? + return t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) : undefined; }); @@ -64687,7 +65155,8 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, ignoreObjects) { + if (ignoreObjects === void 0) { ignoreObjects = false; } var flags = type.flags; if (flags & 4 /* String */) { return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; @@ -64724,7 +65193,7 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 524288 /* Object */) { + if (flags & 524288 /* Object */ && !ignoreObjects) { return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? @@ -64747,14 +65216,17 @@ var ts; return 0 /* None */; } if (flags & 465829888 /* Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */; } if (flags & 1048576 /* Union */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t); }, 0 /* None */); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* None */); } if (flags & 2097152 /* Intersection */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t); }, 16777215 /* All */); + // 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 /* Primitive */)); + return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */); } return 16777215 /* All */; } @@ -64963,6 +65435,9 @@ var ts; function everyType(type, f) { return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } + function everyContainedType(type, f) { + return type.flags & 3145728 /* UnionOrIntersection */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 1048576 /* Union */) { var types = type.types; @@ -66263,7 +66738,16 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); + return filterType(type, function (t) { + if (!isRelated(t, candidate)) { + return true; + } + var constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } // 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. @@ -66358,17 +66842,20 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 78 /* Identifier */) { + if (location.kind === 78 /* Identifier */ || location.kind === 79 /* PrivateIdentifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true); + } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the @@ -66493,7 +66980,6 @@ var ts; } } function checkIdentifier(node, checkMode) { - var _a; var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -66595,7 +67081,7 @@ var ts; } } else if (isAlias) { - declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -66808,7 +67294,7 @@ var ts; break; case 164 /* PropertyDeclaration */: case 163 /* PropertySignature */: - if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } @@ -67451,16 +67937,16 @@ var ts; // In an assignment expression, the right operand is contextually typed by the type of the left operand. // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return getTypeOfExpression(binaryExpression.left); + case 4 /* ThisProperty */: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case 5 /* Property */: - case 1 /* ExportsProperty */: - case 6 /* Prototype */: - case 3 /* PrototypeProperty */: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. @@ -67481,11 +67967,11 @@ var ts; var id = lhs.expression; var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true); if (parentSymbol) { - var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); - if (annotated) { + var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated_1) { var nameStr = ts.getElementOrPropertyAccessName(lhs); if (nameStr !== undefined) { - return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr); + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr); } } return undefined; @@ -67493,9 +67979,15 @@ var ts; } return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; + // falls through case 2 /* ModuleExports */: - case 4 /* ThisProperty */: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); + var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case 7 /* ObjectDefinePropertyValue */: case 8 /* ObjectDefinePropertyExports */: case 9 /* ObjectDefinePrototypeProperty */: @@ -67516,7 +68008,7 @@ var ts; var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true); return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) { + function getContextualTypeForThisPropertyAssignment(binaryExpression) { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { @@ -67528,8 +68020,6 @@ var ts; } } } - if (kind === 2 /* ModuleExports */) - return undefined; var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression); if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return undefined; @@ -67584,6 +68074,10 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { if (hasBindableName(element)) { @@ -67681,10 +68175,10 @@ var ts; return false; } function discriminateContextualTypeByObjectMembers(node, contextualType) { - return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -67793,7 +68287,7 @@ var ts; case 290 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent, contextFlags); case 291 /* SpreadAssignment */: - return getApparentTypeOfContextualType(parent.parent, contextFlags); + return getContextualType(parent.parent, contextFlags); case 200 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); @@ -68189,7 +68683,7 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 32768 /* ArrayLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; } return literalType; } @@ -68346,7 +68840,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -68474,9 +68968,9 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { - result.objectFlags |= 16384 /* JSLiteral */; + result.objectFlags |= 8192 /* JSLiteral */; } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -68566,14 +69060,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var objectFlags = 4096 /* JsxAttributes */; + var objectFlags = 2048 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -68657,7 +69151,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -69159,7 +69653,7 @@ var ts; // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { @@ -69334,6 +69828,23 @@ var ts; if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); } + if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (compilerOptions.target === 99 /* ESNext */ && !useDefineForClassFields)) { + var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); + var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { + if (n === lexicalClass_1) + return "quit"; + if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); + } + } if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -69423,7 +69934,10 @@ var ts; // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + prop && + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) + && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { @@ -69466,6 +69980,7 @@ var ts; var diagnosticMessage; var declarationName = ts.idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { @@ -69571,7 +70086,10 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + var diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : ts.Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -69582,6 +70100,11 @@ var ts; } diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) && + isEmptyObjectType(containingType); + } function typeHasStaticProperty(propName, containingType) { var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); return prop !== undefined && !!prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); @@ -70048,7 +70571,7 @@ var ts; }); if (!inferenceContext) { applyToReturnTypes(contextualSignature, signature, function (source, target) { - inferTypes(context.inferences, source, target, 64 /* ReturnType */); + inferTypes(context.inferences, source, target, 128 /* ReturnType */); }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); @@ -70098,7 +70621,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* 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 @@ -70543,77 +71066,66 @@ var ts; return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - var belowArgCount = Number.NEGATIVE_INFINITY; - var aboveArgCount = Number.POSITIVE_INFINITY; - var argCount = args.length; + var _a; + var spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } + var min = Number.POSITIVE_INFINITY; // smallest parameter count + var max = Number.NEGATIVE_INFINITY; // largest parameter count + var maxBelow = Number.NEGATIVE_INFINITY; // largest parameter count that is smaller than the number of arguments + var minAbove = Number.POSITIVE_INFINITY; // smallest parameter count that is larger than the number of arguments var closestSignature; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var sig = signatures_8[_i]; - var minCount = getMinArgumentCount(sig); - var maxCount = getParameterCount(sig); - if (minCount < argCount && minCount > belowArgCount) - belowArgCount = minCount; - if (argCount < maxCount && maxCount < aboveArgCount) - aboveArgCount = maxCount; - if (minCount < min) { - min = minCount; + var minParameter = getMinArgumentCount(sig); + var maxParameter = getParameterCount(sig); + // smallest/largest parameter counts + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + max = Math.max(max, maxParameter); + // shortest parameter count *longer than the call*/longest parameter count *shorter than the call* + if (minParameter < args.length && minParameter > maxBelow) + maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) + minAbove = maxParameter; } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); - var paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var spanArray; - var related; - var error = hasRestParameter || hasSpreadArgument ? - hasRestParameter && hasSpreadArgument ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - ts.Diagnostics.Expected_0_arguments_but_got_1; - if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { - var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; - if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : - ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); - } - } - if (!hasSpreadArgument && argCount < min) { - var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } - if (hasRestParameter || hasSpreadArgument) { - spanArray = ts.factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); + var parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : ts.Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + // between min and max, but with no matching overload + return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + // too short: put the error span on the call expression, not any of the args + var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined); + return ts.addRelatedInfo(diagnostic, parameterError); } + return diagnostic; } else { - spanArray = ts.factory.createNodeArray(args.slice(max)); - } - var pos = ts.first(spanArray).pos; - var end = ts.last(spanArray).end; - if (end === pos) { - end++; + // too long; error goes on the excess parameters + var errorSpan = ts.factory.createNodeArray(args.slice(max)); + var pos = ts.first(errorSpan).pos; + var end = ts.last(errorSpan).end; + if (end === pos) { + end++; + } + ts.setTextRangePosEnd(errorSpan, pos, end); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - ts.setTextRangePosEnd(spanArray, pos, end); - var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -71706,7 +72218,7 @@ var ts; var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false); if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) { var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + jsAssignmentType.objectFlags |= 8192 /* JSLiteral */; return getIntersectionType([returnType, jsAssignmentType]); } } @@ -72138,7 +72650,14 @@ var ts; } } function assignContextualParameterTypes(signature, context) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; // This signature has already has a contextual inference performed and cached on it! + } + } if (context.thisParameter) { var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { @@ -72531,17 +73050,17 @@ var ts; return; } var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */; + var errorNode = ts.getEffectiveReturnTypeNode(func) || func; if (type && type.flags & 131072 /* Never */) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { // minimal check: function has syntactic return type annotation and no explicit return statements in the body // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -72556,7 +73075,7 @@ var ts; return; } } - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { @@ -72576,7 +73095,7 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; + returnOnlyType.objectFlags |= 524288 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } } @@ -74377,7 +74896,7 @@ var ts; checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { if (!(func.kind === 167 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } @@ -74834,9 +75353,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); })); + ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -74888,15 +75407,18 @@ var ts; var symbol = getSymbolOfNode(node); var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); - if (getter && setter) { + if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) { + getNodeLinks(getter).flags |= 1 /* TypeChecked */; var getterFlags = ts.getEffectiveModifierFlags(getter); var setterFlags = ts.getEffectiveModifierFlags(setter); if ((getterFlags & 128 /* Abstract */) !== (setterFlags & 128 /* Abstract */)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } if (((getterFlags & 16 /* Protected */) && !(setterFlags & (16 /* Protected */ | 8 /* Private */))) || ((getterFlags & 8 /* Private */) && !(setterFlags & 8 /* Private */))) { - error(node.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } var getterType = getAnnotatedAccessorType(getter); var setterType = getAnnotatedAccessorType(setter); @@ -75456,20 +75978,23 @@ var ts; case 298 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: + var node_2 = d; + var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values - if (!ts.isEntityNameExpression(d.expression)) { + if (!ts.isEntityNameExpression(expression)) { return 1 /* ExportValue */; } - d = d.expression; + d = expression; // The below options all declare an Alias, which is allowed to merge with other values within the importing module. // falls through case 261 /* ImportEqualsDeclaration */: case 264 /* NamespaceImport */: case 263 /* ImportClause */: - var result_12 = 0 /* None */; + var result_13 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); - return result_12; + ts.forEach(target.declarations, function (d) { result_13 |= getDeclarationSpaces(d); }); + return result_13; case 250 /* VariableDeclaration */: case 199 /* BindingElement */: case 252 /* FunctionDeclaration */: @@ -76790,11 +77315,6 @@ var ts; return; if (getFalsyFlags(type)) return; - if (getAwaitedTypeOfPromise(type)) { - errorAndMaybeSuggestAwait(condExpr, - /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined, getTypeNameForErrorDisplay(type)); - return; - } var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr; var testedNode = ts.isIdentifier(location) ? location : ts.isPropertyAccessExpression(location) ? location.name @@ -76806,25 +77326,32 @@ var ts; return; } // While it technically should be invalid for any known-truthy value - // to be tested, we de-scope to functions unrefenced in the block as a - // heuristic to identify the most common bugs. There are too many - // false positives for values sourced from type definitions without - // strictNullChecks otherwise. + // to be tested, we de-scope to functions and Promises unreferenced in + // the block as a heuristic to identify the most common bugs. There + // are too many false positives for values sourced from type + // definitions without strictNullChecks otherwise. var callSignatures = getSignaturesOfType(type, 0 /* Call */); - if (callSignatures.length === 0) { + var isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } var testedSymbol = getSymbolAtLocation(testedNode); if (!testedSymbol) { return; } - var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + var isUsed = ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait(location, + /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); + } + else { + error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) { + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { return !!ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); @@ -76861,7 +77388,7 @@ var ts; return ts.forEachChild(childNode, check); }); } - function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) { + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { var isUsed = ts.forEachChild(node.right, function visit(child) { if (ts.isIdentifier(child)) { @@ -78184,7 +78711,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - checkMembersForMissingOverrideModifier(node, type, typeWithThis); + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -78219,12 +78746,16 @@ var ts; checkPropertyInitialization(node); } } - function checkMembersForMissingOverrideModifier(node, type, typeWithThis) { + function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); var baseTypeNode = ts.getEffectiveBaseTypeNode(node); var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); var _loop_24 = function (member) { + if (ts.hasAmbientModifier(member)) { + return "continue"; + } if (ts.isConstructorDeclaration(member)) { ts.forEach(member.parameters, function (param) { if (ts.isParameterPropertyDeclaration(param, member)) { @@ -78240,14 +78771,17 @@ var ts; } function checkClassMember(member, memberIsParameterProperty) { var hasOverride = ts.hasOverrideModifier(member); + var hasStatic = ts.hasStaticModifier(member); if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); if (!declaredProp) { return; } + var thisType = hasStatic ? staticType : typeWithThis; + var baseType = hasStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); var baseClassName = typeToString(baseWithThis); - var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); - var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && !baseProp && hasOverride) { error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } @@ -78258,7 +78792,7 @@ var ts; } if (!baseHasAbstract) { var diag = memberIsParameterProperty ? - ts.Diagnostics.This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; error(member, diag, baseClassName); } @@ -78412,7 +78946,7 @@ var ts; ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { + else if (useDefineForClassFields) { var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 164 /* PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* Transient */) @@ -79288,7 +79822,10 @@ var ts; } } function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + var illegalContextMessage = node.isExportEquals + ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } @@ -79377,10 +79914,12 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, _b = declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (var _i = 0, _b = declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } } @@ -79389,6 +79928,11 @@ var ts; links.exportsChecked = true; } } + function isDuplicatedCommonJSExport(declarations) { + return declarations + && declarations.length > 1 + && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); }); + } function checkSourceElement(node) { if (node) { var saveCurrentNode = currentNode; @@ -79619,7 +80163,8 @@ var ts; if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_1) { + var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent); + if (host_1 || isCallbackTag) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -79627,7 +80172,9 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var lastParamDeclaration = isCallbackTag + ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) + : ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -79843,11 +80390,11 @@ var ts; } switch (location.kind) { case 298 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) + if (!ts.isExternalModule(location)) break; // falls through case 257 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; case 256 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); @@ -79910,6 +80457,16 @@ var ts; }); } } + function copyLocallyVisibleExportSymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + // Similar condition as in `resolveNameHelper` + if (!ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 270 /* NamespaceExport */)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name) { return name.kind === 78 /* Identifier */ && @@ -79949,14 +80506,14 @@ var ts; } return node.parent.kind === 224 /* ExpressionWithTypeArguments */; } - function isJSDocEntryNameReference(node) { + function getJSDocEntryNameReference(node) { while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 303 /* JSDocNameReference */; + return ts.isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node, callback) { var result; @@ -80118,18 +80675,34 @@ var ts; var meaning = name.parent.kind === 174 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (isJSDocEntryNameReference(name)) { - var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); - } - else if (ts.isJSDocLink(name.parent)) { + var jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || ts.isJSDocLink(name.parent)) { var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ true); + var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ false, ts.getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (ts.isQualifiedName(name) && ts.isIdentifier(name.left)) { + // resolve C.m as a static member first + var links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, 0 /* Normal */); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + // then resolve it as an instance member + var s = resolveEntityName(name.left, meaning, /*ignoreErrors*/ false); + if (s) { + var t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } } if (name.parent.kind === 173 /* TypePredicate */) { return resolveEntityName(name, 1 /* FunctionScopedVariable */); } - // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node, ignoreErrors) { @@ -80329,10 +80902,10 @@ var ts; // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { if (expr.parent.kind === 289 /* PropertyAssignment */) { - var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); - var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType; - var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent); - return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex); + var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); + var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; + var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex); } // Array literal assignment - array destructuring pattern var node = ts.cast(expr.parent, ts.isArrayLiteralExpression); @@ -80686,13 +81259,13 @@ var ts; !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && !!parameter.initializer && - !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + !ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameter(parameter) { return !!strictNullChecks && @@ -81400,17 +81973,18 @@ var ts; } break; case 156 /* OverrideKeyword */: + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override"); } else if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); } - else if (flags & 32 /* Static */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "override"); + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); } - if (node.kind === 161 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "override"); + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); } flags |= 16384 /* Override */; lastOverride = modifier; @@ -81422,7 +81996,7 @@ var ts; if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + else if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); } else if (flags & 32 /* Static */) { @@ -81457,9 +82031,6 @@ var ts; else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "override"); - } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } @@ -81472,6 +82043,9 @@ var ts; else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); + } flags |= 32 /* Static */; lastStatic = modifier; break; @@ -81480,7 +82054,7 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } else if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */ && node.kind !== 172 /* IndexSignature */ && node.kind !== 161 /* Parameter */) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; @@ -81521,7 +82095,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + else if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); } else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { @@ -81563,6 +82137,9 @@ var ts; if (flags & 256 /* Async */ && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -81594,7 +82171,7 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } - if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + if (flags & 16384 /* Override */) { return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 } else if (flags & 256 /* Async */) { @@ -81608,10 +82185,10 @@ var ts; else if ((node.kind === 262 /* ImportDeclaration */ || node.kind === 261 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 161 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 161 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -82895,20 +83472,6 @@ var ts; return ts.isDeclarationName(name); } } - function isSomeImportDeclaration(decl) { - switch (decl.kind) { - case 263 /* ImportClause */: // For default import - case 261 /* ImportEqualsDeclaration */: - case 264 /* NamespaceImport */: - case 266 /* ImportSpecifier */: - return true; - case 78 /* Identifier */: - // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 266 /* ImportSpecifier */; - default: - return false; - } - } var JsxNames; (function (JsxNames) { JsxNames.JSX = "JSX"; @@ -87778,10 +88341,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_1 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_1, node); - ts.setCommentRange(clone_1, node); - return clone_1; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -87866,6 +88429,7 @@ var ts; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var shouldTransformPrivateElements = languageVersion < 99 /* ESNext */; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; @@ -87887,7 +88451,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === 99 /* ESNext */) { + || useDefineForClassFields && options.target === 99 /* ESNext */) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -88046,7 +88610,7 @@ var ts; // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } @@ -88357,7 +88921,7 @@ var ts; if (ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. return languageVersion < 99 /* ESNext */; @@ -88380,7 +88944,6 @@ var ts; /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); @@ -88492,7 +89055,7 @@ var ts; function transformProperty(property, receiver) { var _a; // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) - var emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + var emitAssignment = !useDefineForClassFields; var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; @@ -88597,10 +89160,10 @@ var ts; 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; + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; } } } @@ -90762,9 +91325,9 @@ var ts; function convertJsxChildrenToChildrenPropObject(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) + var result_14 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_14 && factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("children", result_14) ]); } var result = ts.mapDefined(children, transformJsxChildToExpression); @@ -92496,7 +93059,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName); var e; - if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) { var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; @@ -93319,13 +93882,13 @@ var ts; loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); - loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); + loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { - var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; @@ -96271,10 +96834,10 @@ var ts; var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { // TODO(rbuckton): Does this need to be parented? - var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); - ts.setSourceMapRange(clone_5, node); - ts.setCommentRange(clone_5, node); - return clone_5; + var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -97268,8 +97831,6 @@ var ts; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(204 /* CallExpression */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(206 /* TaggedTemplateExpression */); // Substitutes expression identifiers with imported/exported symbols. context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. @@ -97280,7 +97841,6 @@ var ts; var currentModuleInfo; // The ExternalModuleInfo for the current file. var noSubstitution; // Set of nodes for which substitution rules should be ignored. var needUMDDynamicImportHelper; - var bindingReferenceCache; return ts.chainBundle(context, transformSourceFile); /** * Transforms the module aspects of a SourceFile. @@ -98527,10 +99087,6 @@ var ts; return substituteExpressionIdentifier(node); case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 204 /* CallExpression */: - return substituteCallExpression(node); - case 206 /* TaggedTemplateExpression */: - return substituteTaggedTemplateExpression(node); case 216 /* PostfixUnaryExpression */: case 215 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); @@ -98538,99 +99094,41 @@ var ts; return node; } /** - * For an Identifier, gets the import or export binding that it references. - * @returns One of the following: - * - An `Identifier` if node references an external helpers module (i.e., `tslib`). - * - A `SourceFile` if the node references an export in the file. - * - An `ImportClause` or `ImportSpecifier` if the node references an import binding. - * - Otherwise, `undefined`. + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. */ - function getImportOrExportBindingReferenceWorker(node) { + function substituteExpressionIdentifier(node) { + var _a, _b; if (ts.getEmitFlags(node) & 4096 /* HelperName */) { var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); if (externalHelpersModuleName) { - return externalHelpersModuleName; + return factory.createPropertyAccessExpression(externalHelpersModuleName, node); } + return node; } else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if ((exportContainer === null || exportContainer === void 0 ? void 0 : exportContainer.kind) === 298 /* SourceFile */) { - return exportContainer; + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { + return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), + /*location*/ node); } var importDeclaration = resolver.getReferencedImportDeclaration(node); - if (importDeclaration && (ts.isImportClause(importDeclaration) || ts.isImportSpecifier(importDeclaration))) { - return importDeclaration; - } - } - return undefined; - } - /** - * For an Identifier, gets the import or export binding that it references. - * @param removeEntry When `false`, the result is cached to avoid recomputing the result in a later substitution. - * When `true`, any cached result for the node is removed. - * @returns One of the following: - * - An `Identifier` if node references an external helpers module (i.e., `tslib`). - * - A `SourceFile` if the node references an export in the file. - * - An `ImportClause` or `ImportSpecifier` if the node references an import binding. - * - Otherwise, `undefined`. - */ - function getImportOrExportBindingReference(node, removeEntry) { - var result = bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.get(node); - if (!result && !(bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.has(node))) { - result = getImportOrExportBindingReferenceWorker(node); - if (!removeEntry) { - bindingReferenceCache || (bindingReferenceCache = new ts.Map()); - bindingReferenceCache.set(node, result); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || importDeclaration), factory.cloneNode(name)), + /*location*/ node); + } } } - else if (removeEntry) { - bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.delete(node); - } - return result; - } - function substituteCallExpression(node) { - if (ts.isIdentifier(node.expression) && getImportOrExportBindingReference(node.expression, /*removeEntry*/ false)) { - return ts.isCallChain(node) ? - factory.updateCallChain(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.expression), node.expression), node.questionDotToken, - /*typeArguments*/ undefined, node.arguments) : - factory.updateCallExpression(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.expression), node.expression), - /*typeArguments*/ undefined, node.arguments); - } return node; } - function substituteTaggedTemplateExpression(node) { - if (ts.isIdentifier(node.tag) && getImportOrExportBindingReference(node.tag, /*removeEntry*/ false)) { - return factory.updateTaggedTemplateExpression(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.tag), node.tag), - /*typeArguments*/ undefined, node.template); - } - return node; - } - /** - * Substitution for an Identifier expression that may contain an imported or exported - * symbol. - * - * @param node The node to substitute. - */ - function substituteExpressionIdentifier(node) { - var _a, _b; - var result = getImportOrExportBindingReference(node, /*removeEntry*/ true); - switch (result === null || result === void 0 ? void 0 : result.kind) { - case 78 /* Identifier */: - return factory.createPropertyAccessExpression(result, node); - case 298 /* SourceFile */: - return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), - /*location*/ node); - case 263 /* ImportClause */: - return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(result.parent), factory.createIdentifier("default")), - /*location*/ node); - case 266 /* ImportSpecifier */: - var name = result.propertyName || result.name; - return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = result.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || result), factory.cloneNode(name)), - /*location*/ node); - default: - return node; - } - } /** * Substitution for a BinaryExpression that may contain an imported or exported symbol. * @@ -99892,7 +100390,7 @@ var ts; return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } /** - * Determines whether the target of a destructuring assigment refers to an exported symbol. + * Determines whether the target of a destructuring assignment refers to an exported symbol. * * @param node The destructuring target. */ @@ -101076,7 +101574,7 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, + var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, /*preferences*/ undefined); if (!ts.pathIsRelative(specifier)) { // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration @@ -101822,7 +102320,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param)) + if (!ts.hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 78 /* Identifier */) { @@ -102607,32 +103105,32 @@ var ts; } ts.transformNodes = transformNodes; ts.nullTransformationContext = { - get factory() { return ts.factory; }, - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: ts.returnUndefined, + factory: ts.factory, getCompilerOptions: function () { return ({}); }, - getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + getEmitHost: ts.notImplemented, getEmitHelperFactory: ts.notImplemented, + startLexicalEnvironment: ts.noop, + resumeLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + endLexicalEnvironment: ts.returnUndefined, setLexicalEnvironmentFlags: ts.noop, getLexicalEnvironmentFlags: function () { return 0; }, - hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + hoistFunctionDeclaration: ts.noop, addInitializationStatement: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop, - addDiagnostic: ts.noop, startBlockScope: ts.noop, endBlockScope: ts.returnUndefined, - addBlockScopedVariable: ts.noop + addBlockScopedVariable: ts.noop, + requestEmitHelper: ts.noop, + readEmitHelpers: ts.notImplemented, + enableSubstitution: ts.noop, + enableEmitNotification: ts.noop, + isSubstitutionEnabled: ts.notImplemented, + isEmitNotificationEnabled: ts.notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, + addDiagnostic: ts.noop, }; })(ts || (ts = {})); var ts; @@ -103381,10 +103879,18 @@ var ts; return outputFiles; } ts.emitUsingBuildInfo = emitUsingBuildInfo; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); var moduleKind = ts.getEmitModuleKind(printerOptions); @@ -103423,8 +103929,10 @@ var ts; var detachedCommentsInfo; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; - var _a = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _a.enter, exitComment = _a.exit; - var preprint = createPreprinter(handlers); + var lastSubstitution; + var currentParenthesizerRule; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + var parenthesizer = ts.factory.parenthesizer; var emitBinaryExpression = createEmitBinaryExpression(); reset(); return { @@ -103624,7 +104132,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - emit(preprint(hint, node)); + pipelineEmit(hint, node, /*parenthesizerRule*/ undefined); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -103657,13 +104165,40 @@ var ts; function getCurrentLineMap() { return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } - function emit(node) { + function emit(node, parenthesizerRule) { if (node === undefined) return; var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - emitWithContext(node, emitWorker); + pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); } + function emitIdentifierName(node) { + if (node === undefined) + return; + pipelineEmit(2 /* IdentifierName */, node, /*parenthesizerRule*/ undefined); + } + function emitExpression(node, parenthesizerRule) { + if (node === undefined) + return; + pipelineEmit(1 /* Expression */, node, parenthesizerRule); + } + function emitJsxAttributeValue(node) { + pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); + } + function beforeEmitNode(node) { + if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { + preserveSourceNewlines = false; + } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; + var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); + pipelinePhase(emitHint, node); + currentParenthesizerRule = undefined; + } function shouldEmitComments(node) { return !commentsDisabled && !ts.isSourceFile(node); } @@ -103674,484 +104209,504 @@ var ts; !ts.isUnparsedSource(node) && !ts.isUnparsedPrepend(node); } - function beforeEmitWithContext(node, shouldEmitComments, shouldEmitSourceMaps) { - onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); - var emitFlags = ts.getEmitFlags(node); - var commentRange = shouldEmitComments ? ts.getCommentRange(node) : undefined; - var sourceMapRange = shouldEmitSourceMaps ? ts.getSourceMapRange(node) : undefined; - if (preserveSourceNewlines && (emitFlags & 134217728 /* IgnoreSourceNewlines */)) { - preserveSourceNewlines = false; - } - // Emit leading comments - if (commentRange) { - emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = true; - } - } - // Emit leading sourcemap - if (sourceMapRange) { - if (ts.isUnparsedNode(node)) { - ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); - var parsed = getParsedSourceMap(node.parent); - if (parsed && sourceMapGenerator) { - sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); + function getPipelinePhase(phase, emitHint, node) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { + return pipelineEmitWithNotification; } - } - else { - var source = sourceMapRange.source || sourceMapSource; - if (node.kind !== 339 /* NotEmittedStatement */ - && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && sourceMapRange.pos >= 0) { - emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + // falls through + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } + return pipelineEmitWithSubstitution; } - if (emitFlags & 64 /* NoNestedSourceMaps */) { - sourceMapsDisabled = true; + // falls through + case 2 /* Comments */: + if (shouldEmitComments(node)) { + return pipelineEmitWithComments; } - } + // falls through + case 3 /* SourceMaps */: + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; + } + // falls through + case 4 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase); } } - function afterEmitWithContext(node, shouldEmitComments, shouldEmitSourceMaps, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines) { - var emitFlags = ts.getEmitFlags(node); - var commentRange = shouldEmitComments ? ts.getCommentRange(node) : undefined; - var sourceMapRange = shouldEmitSourceMaps ? ts.getSourceMapRange(node) : undefined; - // Emit trailing sourcemap - if (sourceMapRange) { - if (!ts.isUnparsedNode(node)) { - if (emitFlags & 64 /* NoNestedSourceMaps */) { - sourceMapsDisabled = false; - } - if (node.kind !== 339 /* NotEmittedStatement */ - && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && sourceMapRange.end >= 0) { - emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); - } - } + function getNextPipelinePhase(currentPhase, emitHint, node) { + return getPipelinePhase(currentPhase + 1, emitHint, node); + } + function pipelineEmitWithNotification(hint, node) { + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + var savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); } - // Emit trailing comments - if (commentRange) { - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = false; - } - emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + else { + pipelineEmitWithHintWorker(hint, node); } - preserveSourceNewlines = savedPreserveSourceNewlines; onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + // clear the parenthesizer rule as we ascend + currentParenthesizerRule = undefined; } - function emitWithContext(node, emitCallback) { - var savedPreserveSourceNewlines = preserveSourceNewlines; - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; - var emitComments = shouldEmitComments(node); - var emitSourceMaps = shouldEmitSourceMaps(node); - beforeEmitWithContext(node, emitComments, emitSourceMaps); - emitCallback(node); - afterEmitWithContext(node, emitComments, emitSourceMaps, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines); - } - function emitWorker(node) { - switch (node.kind) { - // Literals - case 8 /* NumericLiteral */: - case 9 /* BigIntLiteral */: - return emitNumericOrBigIntLiteral(node); - case 10 /* StringLiteral */: - case 13 /* RegularExpressionLiteral */: - case 14 /* NoSubstitutionTemplateLiteral */: - return emitLiteral(node, /*jsxAttributeEscape*/ false); - case 11 /* JsxText */: - return emitJsxText(node); - // Pseudo-literals - case 15 /* TemplateHead */: - case 16 /* TemplateMiddle */: - case 17 /* TemplateTail */: - return emitLiteral(node, /*jsxAttributeEscape*/ false); - // Identifiers and PrivateIdentifiers - case 78 /* Identifier */: - return emitIdentifier(node); - case 79 /* PrivateIdentifier */: - return emitPrivateIdentifier(node); - // Names - case 158 /* QualifiedName */: - return emitQualifiedName(node); - case 159 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - // Signature elements - case 160 /* TypeParameter */: - return emitTypeParameter(node); - case 161 /* Parameter */: - return emitParameter(node); - case 162 /* Decorator */: - return emitDecorator(node); - // Type members - case 163 /* PropertySignature */: - return emitPropertySignature(node); - case 164 /* PropertyDeclaration */: - return emitPropertyDeclaration(node); - case 165 /* MethodSignature */: - return emitMethodSignature(node); - case 166 /* MethodDeclaration */: - return emitMethodDeclaration(node); - case 167 /* Constructor */: - return emitConstructor(node); - case 168 /* GetAccessor */: - case 169 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 170 /* CallSignature */: - return emitCallSignature(node); - case 171 /* ConstructSignature */: - return emitConstructSignature(node); - case 172 /* IndexSignature */: - return emitIndexSignature(node); - // Types - case 173 /* TypePredicate */: - return emitTypePredicate(node); - case 174 /* TypeReference */: - return emitTypeReference(node); - case 175 /* FunctionType */: - return emitFunctionType(node); - case 176 /* ConstructorType */: - return emitConstructorType(node); - case 177 /* TypeQuery */: - return emitTypeQuery(node); - case 178 /* TypeLiteral */: - return emitTypeLiteral(node); - case 179 /* ArrayType */: - return emitArrayType(node); - case 180 /* TupleType */: - return emitTupleType(node); - case 181 /* OptionalType */: - return emitOptionalType(node); - // SyntaxKind.RestType is handled below - case 183 /* UnionType */: - return emitUnionType(node); - case 184 /* IntersectionType */: - return emitIntersectionType(node); - case 185 /* ConditionalType */: - return emitConditionalType(node); - case 186 /* InferType */: - return emitInferType(node); - case 187 /* ParenthesizedType */: - return emitParenthesizedType(node); - case 188 /* ThisType */: - return emitThisType(); - case 189 /* TypeOperator */: - return emitTypeOperator(node); - case 190 /* IndexedAccessType */: - return emitIndexedAccessType(node); - case 191 /* MappedType */: - return emitMappedType(node); - case 192 /* LiteralType */: - return emitLiteralType(node); - case 193 /* NamedTupleMember */: - return emitNamedTupleMember(node); - case 194 /* TemplateLiteralType */: - return emitTemplateType(node); - case 195 /* TemplateLiteralTypeSpan */: - return emitTemplateTypeSpan(node); - case 196 /* ImportType */: - return emitImportTypeNode(node); - // Binding patterns - case 197 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 198 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 199 /* BindingElement */: - return emitBindingElement(node); - // Expressions - case 200 /* ArrayLiteralExpression */: - return emitArrayLiteralExpression(node); - case 201 /* ObjectLiteralExpression */: - return emitObjectLiteralExpression(node); - case 202 /* PropertyAccessExpression */: - return emitPropertyAccessExpression(node); - case 203 /* ElementAccessExpression */: - return emitElementAccessExpression(node); - case 204 /* CallExpression */: - return emitCallExpression(node); - case 205 /* NewExpression */: - return emitNewExpression(node); - case 206 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 207 /* TypeAssertionExpression */: - return emitTypeAssertionExpression(node); - case 208 /* ParenthesizedExpression */: - return emitParenthesizedExpression(node); - case 209 /* FunctionExpression */: - return emitFunctionExpression(node); - case 210 /* ArrowFunction */: - return emitArrowFunction(node); - case 211 /* DeleteExpression */: - return emitDeleteExpression(node); - case 212 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 213 /* VoidExpression */: - return emitVoidExpression(node); - case 214 /* AwaitExpression */: - return emitAwaitExpression(node); - case 215 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 216 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 217 /* BinaryExpression */: - return emitBinaryExpression(node); - case 218 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 219 /* TemplateExpression */: - return emitTemplateExpression(node); - case 220 /* YieldExpression */: - return emitYieldExpression(node); - case 221 /* SpreadElement */: - return emitSpreadExpression(node); - case 222 /* ClassExpression */: - return emitClassExpression(node); - case 223 /* OmittedExpression */: - return; - case 224 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(node); - case 225 /* AsExpression */: - return emitAsExpression(node); - case 226 /* NonNullExpression */: - return emitNonNullExpression(node); - case 227 /* MetaProperty */: - return emitMetaProperty(node); - case 228 /* SyntheticExpression */: - ts.Debug.fail("SyntheticExpression should never be printed."); - break; - // Misc - case 229 /* TemplateSpan */: - return emitTemplateSpan(node); - case 230 /* SemicolonClassElement */: - return emitSemicolonClassElement(); - // Element - case 231 /* Block */: - return emitBlock(node); - case 232 /* EmptyStatement */: - return emitEmptyStatement(/*isEmbeddedStatement*/ false); - case 233 /* VariableStatement */: - return emitVariableStatement(node); - case 234 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 235 /* IfStatement */: - return emitIfStatement(node); - case 236 /* DoStatement */: - return emitDoStatement(node); - case 237 /* WhileStatement */: - return emitWhileStatement(node); - case 238 /* ForStatement */: - return emitForStatement(node); - case 239 /* ForInStatement */: - return emitForInStatement(node); - case 240 /* ForOfStatement */: - return emitForOfStatement(node); - case 241 /* ContinueStatement */: - return emitContinueStatement(node); - case 242 /* BreakStatement */: - return emitBreakStatement(node); - case 243 /* ReturnStatement */: - return emitReturnStatement(node); - case 244 /* WithStatement */: - return emitWithStatement(node); - case 245 /* SwitchStatement */: - return emitSwitchStatement(node); - case 246 /* LabeledStatement */: - return emitLabeledStatement(node); - case 247 /* ThrowStatement */: - return emitThrowStatement(node); - case 248 /* TryStatement */: - return emitTryStatement(node); - case 249 /* DebuggerStatement */: - return emitDebuggerStatement(node); - // Declarations - case 250 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 251 /* VariableDeclarationList */: - return emitVariableDeclarationList(node); - case 252 /* FunctionDeclaration */: - return emitFunctionDeclaration(node); - case 253 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 254 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 255 /* TypeAliasDeclaration */: - return emitTypeAliasDeclaration(node); - case 256 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 257 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 258 /* ModuleBlock */: - return emitModuleBlock(node); - case 259 /* CaseBlock */: - return emitCaseBlock(node); - case 260 /* NamespaceExportDeclaration */: - return emitNamespaceExportDeclaration(node); - case 261 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 262 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 263 /* ImportClause */: - return emitImportClause(node); - case 264 /* NamespaceImport */: - return emitNamespaceImport(node); - case 265 /* NamedImports */: - return emitNamedImports(node); - case 266 /* ImportSpecifier */: - return emitImportSpecifier(node); - case 267 /* ExportAssignment */: - return emitExportAssignment(node); - case 268 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 269 /* NamedExports */: - return emitNamedExports(node); - case 270 /* NamespaceExport */: - return emitNamespaceExport(node); - case 271 /* ExportSpecifier */: - return emitExportSpecifier(node); - case 272 /* MissingDeclaration */: - return; - // Module references - case 273 /* ExternalModuleReference */: - return emitExternalModuleReference(node); - // JSX - case 274 /* JsxElement */: - return emitJsxElement(node); - case 275 /* JsxSelfClosingElement */: - return emitJsxSelfClosingElement(node); - case 278 /* JsxFragment */: - return emitJsxFragment(node); - case 276 /* JsxOpeningElement */: - case 279 /* JsxOpeningFragment */: - return emitJsxOpeningElementOrFragment(node); - case 277 /* JsxClosingElement */: - case 280 /* JsxClosingFragment */: - return emitJsxClosingElementOrFragment(node); - case 281 /* JsxAttribute */: - return emitJsxAttribute(node); - case 282 /* JsxAttributes */: - return emitJsxAttributes(node); - case 283 /* JsxSpreadAttribute */: - return emitJsxSpreadAttribute(node); - case 284 /* JsxExpression */: - return emitJsxExpression(node); - // Clauses - case 285 /* CaseClause */: - return emitCaseClause(node); - case 286 /* DefaultClause */: - return emitDefaultClause(node); - case 287 /* HeritageClause */: - return emitHeritageClause(node); - case 288 /* CatchClause */: - return emitCatchClause(node); - // Property assignments - case 289 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 290 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 291 /* SpreadAssignment */: - return emitSpreadAssignment(node); - // Enum - case 292 /* EnumMember */: - return emitEnumMember(node); - // Unparsed - case 293 /* UnparsedPrologue */: - return writeUnparsedNode(node); - case 300 /* UnparsedSource */: - case 294 /* UnparsedPrepend */: - return emitUnparsedSourceOrPrepend(node); - case 295 /* UnparsedText */: - case 296 /* UnparsedInternalText */: - return emitUnparsedTextLike(node); - case 297 /* UnparsedSyntheticReference */: - return emitUnparsedSyntheticReference(node); - // Top-level nodes - case 298 /* SourceFile */: - return emitSourceFile(node); - case 299 /* Bundle */: - ts.Debug.fail("Bundles should be printed using printBundle"); - break; - // SyntaxKind.UnparsedSource (handled above) - case 301 /* InputFiles */: - ts.Debug.fail("InputFiles should not be printed"); - break; - // JSDoc nodes (only used in codefixes currently) - case 302 /* JSDocTypeExpression */: - return emitJSDocTypeExpression(node); - case 303 /* JSDocNameReference */: - return emitJSDocNameReference(node); - case 304 /* JSDocAllType */: - return writePunctuation("*"); - case 305 /* JSDocUnknownType */: - return writePunctuation("?"); - case 306 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 307 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 308 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 309 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 182 /* RestType */: - case 310 /* JSDocVariadicType */: - return emitRestOrJSDocVariadicType(node); - // SyntaxKind.JSDocNamepathType (missing) - case 312 /* JSDocComment */: - return emitJSDoc(node); - case 314 /* JSDocTypeLiteral */: - return emitJSDocTypeLiteral(node); - case 315 /* JSDocSignature */: - return emitJSDocSignature(node); - case 317 /* JSDocTag */: - case 322 /* JSDocClassTag */: - return emitJSDocSimpleTag(node); - case 318 /* JSDocAugmentsTag */: - case 319 /* JSDocImplementsTag */: - return emitJSDocHeritageTag(node); - // SyntaxKind.JSDocAuthorTag (missing) - // SyntaxKind.JSDocDeprecatedTag (missing) - // SyntaxKind.JSDocClassTag (see JSDocTag, above) - // SyntaxKind.JSDocPublicTag (missing) - // SyntaxKind.JSDocPrivateTag (missing) - // SyntaxKind.JSDocProtectedTag (missing) - // SyntaxKind.JSDocReadonlyTag (missing) - case 328 /* JSDocCallbackTag */: - return emitJSDocCallbackTag(node); - // SyntaxKind.JSDocEnumTag (see below) - case 330 /* JSDocParameterTag */: - case 337 /* JSDocPropertyTag */: - return emitJSDocPropertyLikeTag(node); - case 329 /* JSDocEnumTag */: - case 331 /* JSDocReturnTag */: - case 332 /* JSDocThisTag */: - case 333 /* JSDocTypeTag */: - return emitJSDocSimpleTypedTag(node); - case 334 /* JSDocTemplateTag */: - return emitJSDocTemplateTag(node); - case 335 /* JSDocTypedefTag */: - return emitJSDocTypedefTag(node); - case 336 /* JSDocSeeTag */: - return emitJSDocSeeTag(node); - // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) - // Synthesized list - case 338 /* SyntaxList */: - ts.Debug.fail("SyntaxList should not be printed"); - break; - // Transformation nodes - case 339 /* NotEmittedStatement */: - break; - case 340 /* PartiallyEmittedExpression */: - return emitPartiallyEmittedExpression(node); - case 341 /* CommaListExpression */: - return emitCommaList(node); - case 342 /* MergeDeclarationMarker */: - case 343 /* EndOfDeclarationMarker */: - break; - case 344 /* SyntheticReferenceExpression */: - ts.Debug.fail("SyntheticReferenceExpression should not be printed"); + function pipelineEmitWithHintWorker(hint, node) { + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 6 /* JsxAttributeValue */) + return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } + if (hint === 4 /* Unspecified */) { + switch (node.kind) { + // Pseudo-literals + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return emitLiteral(node, /*jsxAttributeEscape*/ false); + // Identifiers + case 78 /* Identifier */: + return emitIdentifier(node); + // PrivateIdentifiers + case 79 /* PrivateIdentifier */: + return emitPrivateIdentifier(node); + // Parse tree nodes + // Names + case 158 /* QualifiedName */: + return emitQualifiedName(node); + case 159 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 160 /* TypeParameter */: + return emitTypeParameter(node); + case 161 /* Parameter */: + return emitParameter(node); + case 162 /* Decorator */: + return emitDecorator(node); + // Type members + case 163 /* PropertySignature */: + return emitPropertySignature(node); + case 164 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 165 /* MethodSignature */: + return emitMethodSignature(node); + case 166 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 167 /* Constructor */: + return emitConstructor(node); + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 170 /* CallSignature */: + return emitCallSignature(node); + case 171 /* ConstructSignature */: + return emitConstructSignature(node); + case 172 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 173 /* TypePredicate */: + return emitTypePredicate(node); + case 174 /* TypeReference */: + return emitTypeReference(node); + case 175 /* FunctionType */: + return emitFunctionType(node); + case 176 /* ConstructorType */: + return emitConstructorType(node); + case 177 /* TypeQuery */: + return emitTypeQuery(node); + case 178 /* TypeLiteral */: + return emitTypeLiteral(node); + case 179 /* ArrayType */: + return emitArrayType(node); + case 180 /* TupleType */: + return emitTupleType(node); + case 181 /* OptionalType */: + return emitOptionalType(node); + // SyntaxKind.RestType is handled below + case 183 /* UnionType */: + return emitUnionType(node); + case 184 /* IntersectionType */: + return emitIntersectionType(node); + case 185 /* ConditionalType */: + return emitConditionalType(node); + case 186 /* InferType */: + return emitInferType(node); + case 187 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 224 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 188 /* ThisType */: + return emitThisType(); + case 189 /* TypeOperator */: + return emitTypeOperator(node); + case 190 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 191 /* MappedType */: + return emitMappedType(node); + case 192 /* LiteralType */: + return emitLiteralType(node); + case 193 /* NamedTupleMember */: + return emitNamedTupleMember(node); + case 194 /* TemplateLiteralType */: + return emitTemplateType(node); + case 195 /* TemplateLiteralTypeSpan */: + return emitTemplateTypeSpan(node); + case 196 /* ImportType */: + return emitImportTypeNode(node); + // Binding patterns + case 197 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 198 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 199 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 229 /* TemplateSpan */: + return emitTemplateSpan(node); + case 230 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 231 /* Block */: + return emitBlock(node); + case 233 /* VariableStatement */: + return emitVariableStatement(node); + case 232 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 234 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 235 /* IfStatement */: + return emitIfStatement(node); + case 236 /* DoStatement */: + return emitDoStatement(node); + case 237 /* WhileStatement */: + return emitWhileStatement(node); + case 238 /* ForStatement */: + return emitForStatement(node); + case 239 /* ForInStatement */: + return emitForInStatement(node); + case 240 /* ForOfStatement */: + return emitForOfStatement(node); + case 241 /* ContinueStatement */: + return emitContinueStatement(node); + case 242 /* BreakStatement */: + return emitBreakStatement(node); + case 243 /* ReturnStatement */: + return emitReturnStatement(node); + case 244 /* WithStatement */: + return emitWithStatement(node); + case 245 /* SwitchStatement */: + return emitSwitchStatement(node); + case 246 /* LabeledStatement */: + return emitLabeledStatement(node); + case 247 /* ThrowStatement */: + return emitThrowStatement(node); + case 248 /* TryStatement */: + return emitTryStatement(node); + case 249 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 250 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 251 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 252 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 253 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 254 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 255 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 256 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 257 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 258 /* ModuleBlock */: + return emitModuleBlock(node); + case 259 /* CaseBlock */: + return emitCaseBlock(node); + case 260 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 261 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 262 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 263 /* ImportClause */: + return emitImportClause(node); + case 264 /* NamespaceImport */: + return emitNamespaceImport(node); + case 270 /* NamespaceExport */: + return emitNamespaceExport(node); + case 265 /* NamedImports */: + return emitNamedImports(node); + case 266 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 267 /* ExportAssignment */: + return emitExportAssignment(node); + case 268 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 269 /* NamedExports */: + return emitNamedExports(node); + case 271 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 272 /* MissingDeclaration */: + return; + // Module references + case 273 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 11 /* JsxText */: + return emitJsxText(node); + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 277 /* JsxClosingElement */: + case 280 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 281 /* JsxAttribute */: + return emitJsxAttribute(node); + case 282 /* JsxAttributes */: + return emitJsxAttributes(node); + case 283 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 284 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 285 /* CaseClause */: + return emitCaseClause(node); + case 286 /* DefaultClause */: + return emitDefaultClause(node); + case 287 /* HeritageClause */: + return emitHeritageClause(node); + case 288 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 289 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 290 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 291 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 292 /* EnumMember */: + return emitEnumMember(node); + // Unparsed + case 293 /* UnparsedPrologue */: + return writeUnparsedNode(node); + case 300 /* UnparsedSource */: + case 294 /* UnparsedPrepend */: + return emitUnparsedSourceOrPrepend(node); + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: + return emitUnparsedTextLike(node); + case 297 /* UnparsedSyntheticReference */: + return emitUnparsedSyntheticReference(node); + // Top-level nodes + case 298 /* SourceFile */: + return emitSourceFile(node); + case 299 /* Bundle */: + return ts.Debug.fail("Bundles should be printed using printBundle"); + // SyntaxKind.UnparsedSource (handled above) + case 301 /* InputFiles */: + return ts.Debug.fail("InputFiles should not be printed"); + // JSDoc nodes (only used in codefixes currently) + case 302 /* JSDocTypeExpression */: + return emitJSDocTypeExpression(node); + case 303 /* JSDocNameReference */: + return emitJSDocNameReference(node); + case 304 /* JSDocAllType */: + return writePunctuation("*"); + case 305 /* JSDocUnknownType */: + return writePunctuation("?"); + case 306 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 307 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 308 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 309 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 182 /* RestType */: + case 310 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + case 311 /* JSDocNamepathType */: + return; + case 312 /* JSDocComment */: + return emitJSDoc(node); + case 314 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 315 /* JSDocSignature */: + return emitJSDocSignature(node); + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + return emitJSDocSimpleTag(node); + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + return emitJSDocHeritageTag(node); + case 320 /* JSDocAuthorTag */: + case 321 /* JSDocDeprecatedTag */: + return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 327 /* JSDocOverrideTag */: + return; + case 328 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + // SyntaxKind.JSDocEnumTag (see below) + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 329 /* JSDocEnumTag */: + case 331 /* JSDocReturnTag */: + case 332 /* JSDocThisTag */: + case 333 /* JSDocTypeTag */: + return emitJSDocSimpleTypedTag(node); + case 334 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 335 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 336 /* JSDocSeeTag */: + return emitJSDocSeeTag(node); + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) + // Transformation nodes + case 339 /* NotEmittedStatement */: + case 343 /* EndOfDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: + return; + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + if (substituteNode !== ts.noEmitSubstitution) { + var substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } + } + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node, /*jsxAttributeEscape*/ false); + // Identifiers + case 78 /* Identifier */: + return emitIdentifier(node); + // Expressions + case 200 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 201 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 202 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 203 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 204 /* CallExpression */: + return emitCallExpression(node); + case 205 /* NewExpression */: + return emitNewExpression(node); + case 206 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 207 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 208 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 209 /* FunctionExpression */: + return emitFunctionExpression(node); + case 210 /* ArrowFunction */: + return emitArrowFunction(node); + case 211 /* DeleteExpression */: + return emitDeleteExpression(node); + case 212 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 213 /* VoidExpression */: + return emitVoidExpression(node); + case 214 /* AwaitExpression */: + return emitAwaitExpression(node); + case 215 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 216 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 217 /* BinaryExpression */: + return emitBinaryExpression(node); + case 218 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 219 /* TemplateExpression */: + return emitTemplateExpression(node); + case 220 /* YieldExpression */: + return emitYieldExpression(node); + case 221 /* SpreadElement */: + return emitSpreadElement(node); + case 222 /* ClassExpression */: + return emitClassExpression(node); + case 223 /* OmittedExpression */: + return; + case 225 /* AsExpression */: + return emitAsExpression(node); + case 226 /* NonNullExpression */: + return emitNonNullExpression(node); + case 227 /* MetaProperty */: + return emitMetaProperty(node); + case 228 /* SyntheticExpression */: + return ts.Debug.fail("SyntheticExpression should never be printed."); + // JSX + case 274 /* JsxElement */: + return emitJsxElement(node); + case 275 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 278 /* JsxFragment */: + return emitJsxFragment(node); + // Synthesized list + case 338 /* SyntaxList */: + return ts.Debug.fail("SyntaxList should not be printed"); + // Transformation nodes + case 339 /* NotEmittedStatement */: + return; + case 340 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 341 /* CommaListExpression */: + return emitCommaList(node); + case 342 /* MergeDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: + return; + case 344 /* SyntheticReferenceExpression */: + return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); + } } if (ts.isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); if (ts.isTokenKind(node.kind)) return writeTokenNode(node, writePunctuation); + ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); } function emitMappedTypeParameter(node) { emit(node.name); @@ -104160,6 +104715,13 @@ var ts; writeSpace(); emit(node.constraint); } + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node); + ts.Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); + } function getHelpersFromBundledSourceFiles(bundle) { var result; if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) { @@ -104262,9 +104824,6 @@ var ts; writeStringLiteral(text); } } - function emitStringLiteralWithJsxAttributeEscape(node) { - emitLiteral(node, /*jsxAttributeEscape*/ true); - } // SyntaxKind.UnparsedSource // SyntaxKind.UnparsedPrepend function emitUnparsedSourceOrPrepend(unparsed) { @@ -104323,7 +104882,7 @@ var ts; } function emitEntityName(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -104331,7 +104890,7 @@ var ts; } function emitComputedPropertyName(node) { writePunctuation("["); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } // @@ -104365,11 +104924,11 @@ 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); + 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); } function emitDecorator(decorator) { writePunctuation("@"); - emit(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } // // Type members @@ -104534,7 +105093,7 @@ var ts; writePunctuation("}"); } function emitArrayType(node) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -104557,21 +105116,21 @@ var ts; emit(node.type); } function emitOptionalType(node) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 516 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node) { - emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -104597,10 +105156,10 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -104623,7 +105182,7 @@ var ts; writeSpace(); } writePunctuation("["); - emitWithContext(node.typeParameter, emitMappedTypeParameter); + pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter); if (node.nameType) { writeSpace(); writeKeyword("as"); @@ -104651,7 +105210,7 @@ var ts; writePunctuation("}"); } function emitLiteralType(node) { - emit(node.literal); + emitExpression(node.literal); } function emitTemplateType(node) { emit(node.head); @@ -104693,7 +105252,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // Expressions @@ -104701,7 +105260,7 @@ var ts; function emitArrayLiteralExpression(node) { var elements = node.elements; var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; - emitList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -104717,7 +105276,7 @@ var ts; } } function emitPropertyAccessExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos); var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); var linesAfterDot = getLinesBetweenNodes(node, token, node.name); @@ -104759,41 +105318,41 @@ var ts; } } function emitElementAccessExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); - emit(node.argumentExpression); + emitExpression(node.argumentExpression); emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitList(node, node.arguments, 2576 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitList(node, node.arguments, 18960 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node) { - emit(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); - emit(node.template); + emitExpression(node.template); } function emitTypeAssertionExpression(node) { writePunctuation("<"); emit(node.type); writePunctuation(">"); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emit(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -104817,29 +105376,29 @@ var ts; function emitDeleteExpression(node) { emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node) { writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emit(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node) { // In some cases, we need to emit a space between the operator and the operand. One obvious case @@ -104860,11 +105419,11 @@ var ts; || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { - emit(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } function createEmitBinaryExpression() { - return ts.createBinaryExpressionTrampoline(onEnter, maybeEmitExpression, onOperator, maybeEmitExpression, onExit, /*foldState*/ undefined); + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); function onEnter(node, state) { if (state) { state.stackIndex++; @@ -104874,7 +105433,12 @@ var ts; state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); - beforeEmitWithContext(node, emitComments_1, emitSourceMaps); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (emitComments_1) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); } else { state = { @@ -104889,6 +105453,9 @@ var ts; } return state; } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } function onOperator(operatorToken, _state, node) { var isCommaOperator = operatorToken.kind !== 27 /* CommaToken */; var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); @@ -104899,6 +105466,9 @@ var ts; emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } function onExit(node, state) { var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); @@ -104910,16 +105480,35 @@ var ts; var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex]; var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex]; - afterEmitWithContext(node, shouldEmitComments_1, shouldEmitSourceMaps_1, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines); + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps_1) + emitSourceMapsAfterNode(node); + if (shouldEmitComments_1) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); state.stackIndex--; } } - function maybeEmitExpression(next) { - // Push a new frame for binary expressions, otherwise emit all other expressions. - if (ts.isBinaryExpression(next)) { - return next; + function maybeEmitExpression(next, parent, side) { + var parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); + var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next); + if (pipelinePhase === pipelineEmitWithSubstitution) { + ts.Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression)); + pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next); + lastSubstitution = undefined; } - emit(next); + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (ts.isBinaryExpression(next)) { + return next; + } + } + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1 /* Expression */, next); } } function emitConditionalExpression(node) { @@ -104927,16 +105516,16 @@ var ts; var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emit(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true); - emit(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true); - emit(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { @@ -104946,22 +105535,22 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node) { + function emitSpreadElement(node) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emit(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -104970,7 +105559,7 @@ var ts; } } function emitNonNullExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } function emitMetaProperty(node) { @@ -104982,7 +105571,7 @@ var ts; // Misc // function emitTemplateSpan(node) { - emit(node.expression); + emitExpression(node.expression); emit(node.literal); } // @@ -105012,11 +105601,8 @@ var ts; writeTrailingSemicolon(); } } - function emitEmbeddedEmptyStatement(_node) { - emitEmptyStatement(/*isEmbeddedStatement*/ true); - } function emitExpressionStatement(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); // Emit semicolon in non json files // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { @@ -105027,7 +105613,7 @@ var ts; var openParenPos = emitTokenWithComment(98 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { @@ -105046,7 +105632,7 @@ var ts; var openParenPos = emitTokenWithComment(114 /* WhileKeyword */, startPos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); } function emitDoStatement(node) { @@ -105085,7 +105671,7 @@ var ts; writeSpace(); emitTokenWithComment(100 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -105098,7 +105684,7 @@ var ts; writeSpace(); emitTokenWithComment(157 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -105108,7 +105694,7 @@ var ts; emit(node); } else { - emit(node); + emitExpression(node); } } } @@ -105155,7 +105741,7 @@ var ts; var openParenPos = emitTokenWithComment(115 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -105163,7 +105749,7 @@ var ts; var openParenPos = emitTokenWithComment(106 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); @@ -105205,7 +105791,7 @@ var ts; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); @@ -105221,7 +105807,7 @@ var ts; writeKeyword("function"); emit(node.asteriskToken); writeSpace(); - emit(node.name); + emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } function emitSignatureAndBody(node, emitSignatureHead) { @@ -105245,7 +105831,7 @@ var ts; else { emitSignatureHead(node); writeSpace(); - emit(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -105320,7 +105906,7 @@ var ts; increaseIndent(); } else { - emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, /*parenthesizerRule*/ undefined, statementOffset); } } function emitClassDeclaration(node) { @@ -105333,7 +105919,7 @@ var ts; writeKeyword("class"); if (node.name) { writeSpace(); - emit(node.name); + emitIdentifierName(node.name); } var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { @@ -105431,7 +106017,7 @@ var ts; } function emitModuleReference(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -105447,7 +106033,7 @@ var ts; emitTokenWithComment(153 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } - emit(node.moduleSpecifier); + emitExpression(node.moduleSpecifier); writeTrailingSemicolon(); } function emitImportClause(node) { @@ -105485,7 +106071,9 @@ var ts; emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); - emit(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(62 /* EqualsToken */) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -105506,7 +106094,7 @@ var ts; var fromPos = node.exportClause ? node.exportClause.end : nextPos; emitTokenWithComment(153 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); - emit(node.moduleSpecifier); + emitExpression(node.moduleSpecifier); } writeTrailingSemicolon(); } @@ -105553,7 +106141,7 @@ var ts; function emitExternalModuleReference(node) { writeKeyword("require"); writePunctuation("("); - emit(node.expression); + emitExpression(node.expression); writePunctuation(")"); } // @@ -105605,17 +106193,13 @@ var ts; function emitJsxAttributes(node) { emitList(node, node.properties, 262656 /* JsxElementAttributes */); } - function emitJsxAttributeValue(node) { - var emitCallback = ts.isStringLiteral(node) ? emitStringLiteralWithJsxAttributeEscape : emitWorker; - emitWithContext(node, emitCallback); - } function emitJsxAttribute(node) { emit(node.name); emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue); } function emitJsxSpreadAttribute(node) { writePunctuation("{..."); - emit(node.expression); + emitExpression(node.expression); writePunctuation("}"); } function hasTrailingCommentsAtPosition(pos) { @@ -105640,7 +106224,7 @@ var ts; } var end = emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); emit(node.dotDotDotToken); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(19 /* CloseBraceToken */, ((_a = node.expression) === null || _a === void 0 ? void 0 : _a.end) || end, writePunctuation, node); if (isMultiline) { writer.decreaseIndent(); @@ -105649,7 +106233,7 @@ var ts; } function emitJsxTagName(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -105661,7 +106245,7 @@ var ts; function emitCaseClause(node) { emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { @@ -105722,7 +106306,7 @@ var ts; var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emit(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node) { emit(node.name); @@ -105730,13 +106314,13 @@ var ts; writeSpace(); writePunctuation("="); writeSpace(); - emit(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node) { if (node.expression) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } // @@ -105744,7 +106328,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // JSDoc @@ -105989,15 +106573,15 @@ var ts; emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + emitList(node, statements, 1 /* MultiLine */, /*parenthesizerRule*/ undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } // Transformation nodes function emitPartiallyEmittedExpression(node) { - emit(node.expression); + emitExpression(node.expression); } function emitCommaList(node) { - emitList(node, node.elements, 528 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -106143,12 +106727,12 @@ var ts; emit(node); } } - function emitInitializer(node, equalCommentStartPos, container) { + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); - emit(node); + emitExpression(node, parenthesizerRule); } } function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { @@ -106163,10 +106747,10 @@ var ts; emit(node); } } - function emitExpressionWithLeadingSpace(node) { + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { if (node) { writeSpace(); - emit(node); + emitExpression(node, parenthesizerRule); } } function emitWithTrailingSpace(node) { @@ -106184,7 +106768,7 @@ var ts; writeLine(); increaseIndent(); if (ts.isEmptyStatement(node)) { - emitWithContext(node, emitEmbeddedEmptyStatement); + pipelineEmit(5 /* EmbeddedStatement */, node); } else { emit(node); @@ -106196,7 +106780,7 @@ var ts; emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures @@ -106257,7 +106841,13 @@ var ts; break; } } - function emitList(parentNode, children, format, start, count) { + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; @@ -106361,7 +106951,12 @@ var ts; shouldEmitInterveningComments = mayEmitInterveningComments; } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); shouldDecreaseIndentAfterEmit = false; @@ -107097,6 +107692,33 @@ var ts; return node; } // Comments + function pipelineEmitWithComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit leading comments + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit trailing comments + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; @@ -107392,6 +108014,50 @@ var ts; } return node.parsedSourceMap || undefined; } + function pipelineEmitWithSourceMaps(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node); + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit leading sourcemap + if (ts.isUnparsedNode(node)) { + ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); + var parsed = getParsedSourceMap(node.parent); + if (parsed && sourceMapGenerator) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); + } + } + else { + var source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 339 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + } + } + } + function emitSourceMapsAfterNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit trailing sourcemap + if (!ts.isUnparsedNode(node)) { + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = false; + } + if (node.kind !== 339 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); + } + } + } /** * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source */ @@ -107484,736 +108150,6 @@ var ts; } } ts.createPrinter = createPrinter; - var PreprintPipelinePhase; - (function (PreprintPipelinePhase) { - PreprintPipelinePhase[PreprintPipelinePhase["Notification"] = 0] = "Notification"; - PreprintPipelinePhase[PreprintPipelinePhase["Substitution"] = 1] = "Substitution"; - PreprintPipelinePhase[PreprintPipelinePhase["Visit"] = 2] = "Visit"; - })(PreprintPipelinePhase || (PreprintPipelinePhase = {})); - function createPreprinter(handlers) { - var _a = handlers.substituteNode, substituteNode = _a === void 0 ? ts.noEmitSubstitution : _a, _b = handlers.onEmitNode, onEmitNode = _b === void 0 ? ts.noEmitNotification : _b, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled; - var pipelineResult; - // Outer visitors - // - // These visitors are invoked by inner visitors to re-enter the pipeline - // for notification and substitution. - var visit = makeVisitor(pipelineVisitorForUnspecified); - var visitSourceFile = makeVisitor(pipelineVisitorForSourceFile, ts.isSourceFile); - var visitIdentifierName = makeVisitor(pipelineVisitorForIdentifierName, ts.isIdentifier); - var visitModuleName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isModuleName); - var visitPropertyName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isPropertyName); - var visitMemberName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isMemberName); - var visitBindingName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isBindingName); - var visitEntityName = makeVisitor(pipelineVisitorForIdentifierReferenceOrUnspecified, ts.isEntityName); - var visitExpression = makeVisitor(pipelineVisitorForExpression, ts.isExpression); - var visitForInitializer = makeVisitor(pipelineVisitorForForInitializer, ts.isForInitializer); - var visitTypeNode = makeVisitor(pipelineVisitorForUnspecified, ts.isTypeNode); - var visitEmbeddedStatement = makeVisitor(pipelineVisitorForEmbeddedStatement, ts.isStatement, ts.factory.liftToBlock); - var visitJsxAttributeValue = makeVisitor(pipelineVisitorForJsxAttributeValue, ts.isStringLiteralOrJsxExpression); - var visitMappedTypeParameter = makeVisitor(pipelineVisitorForMappedTypeParameter, ts.isTypeParameterDeclaration); - var visitConciseBody = makeVisitor(pipelineVisitorForConciseBody, ts.isConciseBody); - var visitFunctionBody = makeVisitor(pipelineVisitorForUnspecified, ts.isFunctionBody); - var visitList = makeListVisitor(pipelineVisitorForUnspecified); - var visitTypeNodeList = makeListVisitor(pipelineVisitorForUnspecified, ts.isTypeNode); - var visitExpressionList = makeListVisitor(pipelineVisitorForExpression, ts.isExpression); - var visitParameterList = makeListVisitor(pipelineVisitorForUnspecified, ts.isParameter); - function makeVisitor(outerVisitor, defaultTest, lift) { - function visit(node, test) { - return ts.visitNode(node, outerVisitor, test || defaultTest, lift); - } - return visit; - } - function makeListVisitor(outerVisitor, defaultTest) { - function visitList(nodes, test) { - if (test === void 0) { test = defaultTest || ts.returnTrue; } - return ts.visitNodes(nodes, outerVisitor, test); - } - return visitList; - } - // Pipeline Visitors - // - // These visitors execute our existing pipeline logic for notification and substitution, - // but adapted to our visitor pattern. In some cases, we refine the `EmitHint` we pass - // to the `onEmitNode` and `substituteNode` APIs to ensure they receive the appropriate - // context. - // - // For example, the ConciseBody of an arrow function could be an Identifier, in which - // case we would want to use `EmitHint.Expression` to ensure we treat the identifier - // as an expression during substitution. - function pipelineVisitorForSourceFile(node) { return pipelineVisitorWorker(0 /* SourceFile */, node); } - function pipelineVisitorForExpression(node) { return pipelineVisitorWorker(1 /* Expression */, node); } - function pipelineVisitorForIdentifierName(node) { return pipelineVisitorWorker(2 /* IdentifierName */, node); } - function pipelineVisitorForIdentifierNameOrUnspecified(node) { return pipelineVisitorWorker(ts.isIdentifier(node) ? 2 /* IdentifierName */ : 4 /* Unspecified */, node); } - function pipelineVisitorForIdentifierReferenceOrUnspecified(node) { return pipelineVisitorWorker(ts.isIdentifier(node) ? 1 /* Expression */ : 4 /* Unspecified */, node); } - function pipelineVisitorForForInitializer(node) { return pipelineVisitorWorker(ts.isVariableDeclarationList(node) ? 4 /* Unspecified */ : 1 /* Expression */, node); } - function pipelineVisitorForMappedTypeParameter(node) { return pipelineVisitorWorker(3 /* MappedTypeParameter */, node); } - function pipelineVisitorForEmbeddedStatement(node) { return pipelineVisitorWorker(ts.isEmptyStatement(node) ? 5 /* EmbeddedStatement */ : 4 /* Unspecified */, node); } - function pipelineVisitorForJsxAttributeValue(node) { return pipelineVisitorWorker(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); } - function pipelineVisitorForConciseBody(node) { return pipelineVisitorWorker(ts.isBlock(node) ? 4 /* Unspecified */ : 1 /* Expression */, node); } - function pipelineVisitorForUnspecified(node) { return pipelineVisitorWorker(4 /* Unspecified */, node); } - /** - * Adapts the emit pipeline API to work with the visitor API - */ - function pipelineVisitorWorker(hint, node) { - resetPipelineResult(); - // Get the first supported pipeline phase for this node and evaluate it. We can skip several stack - // frames if we aren't doing emit notification, so we check for substitution and direct callbacks - // and execute those immediately. - var pipelinePhase = getPipelinePhase(0 /* Notification */, node); - if (pipelinePhase === pipelineVisitDirect) { - return visitor(hint, node); - } - if (pipelinePhase === pipelineVisitWithSubstitution) { - // The next phase after substitution is always direct visitation, so we can reduce the call stack - // depth by calling the visitor directly. - return visitor(hint, substituteNode(hint, node)); - } - pipelinePhase(hint, node); - ts.Debug.assertIsDefined(pipelineResult); - var result = pipelineResult; - resetPipelineResult(); - return result; - } - function resetPipelineResult() { - pipelineResult = undefined; - } - /** - * Gets the pipeline callback to pass to the relevant API (i.e., `substituteNode` or `onEmitNode`) - */ - function getPipelinePhase(phase, node) { - switch (phase) { - case 0 /* Notification */: - if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { - return pipelineVisitWithNotification; - } - // falls through - case 1 /* Substitution */: - if (substituteNode !== ts.noEmitSubstitution) { - return pipelineVisitWithSubstitution; - } - // falls through - default: - return pipelineVisitDirect; - } - } - /** - * A callback that can be evaluated to trigger emit notification as part of the emit pipeline. - */ - function pipelineVisitWithNotification(hint, node) { - onEmitNode(hint, node, getPipelinePhase(1 /* Substitution */, node)); - } - /** - * A callback that can be evaluated to trigger JIT substitution as part of the emit pipeline. - */ - function pipelineVisitWithSubstitution(hint, node) { - // Next phase is always direct visitation, so we can reduce the call stack - // depth by calling the visitor directly. - pipelineResult = visitor(hint, substituteNode(hint, node)); - } - /** - * A callback that can be evaluated to visit the subtree of a node. - */ - function pipelineVisitDirect(hint, node) { - pipelineResult = visitor(hint, node); - } - /** - * Re-enters the visitor pattern from the pipeline pattern to perform - * tree updates and trigger parenthesization rules. - */ - function visitor(hint, node) { - // This should align with the assertions in `pipelineEmitWithHint`. - if (hint === 0 /* SourceFile */) - return preprintSourceFile(ts.cast(node, ts.isSourceFile)); - if (hint === 2 /* IdentifierName */) - return preprintIdentifier(ts.cast(node, ts.isIdentifier)); - if (hint === 6 /* JsxAttributeValue */) - return ts.cast(node, ts.isStringLiteral); - if (hint === 3 /* MappedTypeParameter */) - return preprintTypeParameterDeclaration(ts.cast(node, ts.isTypeParameterDeclaration)); - if (hint === 5 /* EmbeddedStatement */) - return ts.cast(node, ts.isEmptyStatement); - var kind = node.kind; - // No need to visit nodes without children. - if ((kind > 0 /* FirstToken */ && kind <= 157 /* LastToken */) || kind === 188 /* ThisType */) { - return node; - } - if (hint === 4 /* Unspecified */) { - if (ts.isKeyword(node.kind)) - return node; - switch (node.kind) { - // Identifiers - case 78 /* Identifier */: - return preprintIdentifier(node); - // Names - case 158 /* QualifiedName */: - ts.Debug.type(node); - return ts.factory.updateQualifiedName(node, visitEntityName(node.left), visitIdentifierName(node.right)); - case 159 /* ComputedPropertyName */: - ts.Debug.type(node); - return ts.factory.updateComputedPropertyName(node, visitExpression(node.expression)); - // Signature elements - case 160 /* TypeParameter */: - return preprintTypeParameterDeclaration(node); - case 161 /* Parameter */: - ts.Debug.type(node); - return ts.factory.updateParameterDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.dotDotDotToken, ts.isDotDotDotToken), visitBindingName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 162 /* Decorator */: - ts.Debug.type(node); - return ts.factory.updateDecorator(node, visitExpression(node.expression)); - // Type members - case 163 /* PropertySignature */: - ts.Debug.type(node); - return ts.factory.updatePropertySignature(node, visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type)); - case 164 /* PropertyDeclaration */: - ts.Debug.type(node); - return ts.factory.updatePropertyDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken || node.exclamationToken, ts.isQuestionOrExclamationToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 165 /* MethodSignature */: - ts.Debug.type(node); - return ts.factory.updateMethodSignature(node, visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 166 /* MethodDeclaration */: - ts.Debug.type(node); - return ts.factory.updateMethodDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 167 /* Constructor */: - ts.Debug.type(node); - return ts.factory.updateConstructorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitParameterList(node.parameters), visitFunctionBody(node.body)); - case 168 /* GetAccessor */: - ts.Debug.type(node); - return ts.factory.updateGetAccessorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 169 /* SetAccessor */: - ts.Debug.type(node); - return ts.factory.updateSetAccessorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visitParameterList(node.parameters), visitFunctionBody(node.body)); - case 170 /* CallSignature */: - ts.Debug.type(node); - return ts.factory.updateCallSignature(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 171 /* ConstructSignature */: - ts.Debug.type(node); - return ts.factory.updateConstructSignature(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 172 /* IndexSignature */: - ts.Debug.type(node); - return ts.factory.updateIndexSignature(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitParameterList(node.parameters), visitTypeNode(node.type)); - // Types - case 173 /* TypePredicate */: - ts.Debug.type(node); - return ts.factory.updateTypePredicateNode(node, visit(node.assertsModifier, ts.isAssertsKeyword), visit(node.parameterName, ts.isIdentifierOrThisTypeNode), visitTypeNode(node.type)); - case 174 /* TypeReference */: - ts.Debug.type(node); - return ts.factory.updateTypeReferenceNode(node, visitEntityName(node.typeName), visitTypeNodeList(node.typeArguments)); - case 175 /* FunctionType */: - ts.Debug.type(node); - return ts.factory.updateFunctionTypeNode(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), ts.visitNodes(node.parameters, pipelineVisitorForUnspecified, ts.isParameterDeclaration), visitTypeNode(node.type)); - case 176 /* ConstructorType */: - ts.Debug.type(node); - return ts.factory.updateConstructorTypeNode(node, ts.visitNodes(node.modifiers, pipelineVisitorForUnspecified, ts.isModifier), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 177 /* TypeQuery */: - ts.Debug.type(node); - return ts.factory.updateTypeQueryNode(node, visitEntityName(node.exprName)); - case 178 /* TypeLiteral */: - ts.Debug.type(node); - return ts.factory.updateTypeLiteralNode(node, visitList(node.members, ts.isTypeElement)); - case 179 /* ArrayType */: - ts.Debug.type(node); - return ts.factory.updateArrayTypeNode(node, visitTypeNode(node.elementType)); - case 180 /* TupleType */: - ts.Debug.type(node); - return ts.factory.updateTupleTypeNode(node, visitTypeNodeList(node.elements)); - case 181 /* OptionalType */: - ts.Debug.type(node); - return ts.factory.updateOptionalTypeNode(node, visitTypeNode(node.type)); - case 182 /* RestType */: - ts.Debug.type(node); - return ts.factory.updateRestTypeNode(node, visitTypeNode(node.type)); - case 183 /* UnionType */: - ts.Debug.type(node); - return ts.factory.updateUnionTypeNode(node, visitTypeNodeList(node.types)); - case 184 /* IntersectionType */: - ts.Debug.type(node); - return ts.factory.updateIntersectionTypeNode(node, visitTypeNodeList(node.types)); - case 185 /* ConditionalType */: - ts.Debug.type(node); - return ts.factory.updateConditionalTypeNode(node, visitTypeNode(node.checkType), visitTypeNode(node.extendsType), visitTypeNode(node.trueType), visitTypeNode(node.falseType)); - case 186 /* InferType */: - ts.Debug.type(node); - return ts.factory.updateInferTypeNode(node, visit(node.typeParameter, ts.isTypeParameterDeclaration)); - case 196 /* ImportType */: - ts.Debug.type(node); - return ts.factory.updateImportTypeNode(node, visitTypeNode(node.argument), visitEntityName(node.qualifier), visitTypeNodeList(node.typeArguments), node.isTypeOf); - case 193 /* NamedTupleMember */: - ts.Debug.type(node); - return ts.factory.updateNamedTupleMember(node, visit(node.dotDotDotToken, ts.isDotDotDotToken), visitIdentifierName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type)); - case 187 /* ParenthesizedType */: - ts.Debug.type(node); - return ts.factory.updateParenthesizedType(node, visitTypeNode(node.type)); - case 224 /* ExpressionWithTypeArguments */: - ts.Debug.type(node); - return ts.factory.updateExpressionWithTypeArguments(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments)); - case 189 /* TypeOperator */: - ts.Debug.type(node); - return ts.factory.updateTypeOperatorNode(node, visitTypeNode(node.type)); - case 190 /* IndexedAccessType */: - ts.Debug.type(node); - return ts.factory.updateIndexedAccessTypeNode(node, visitTypeNode(node.objectType), visitTypeNode(node.indexType)); - case 191 /* MappedType */: - ts.Debug.type(node); - return ts.factory.updateMappedTypeNode(node, visit(node.readonlyToken, ts.isReadonlyKeywordOrPlusOrMinusToken), visitMappedTypeParameter(node.typeParameter), visitTypeNode(node.nameType), visit(node.questionToken, ts.isQuestionOrPlusOrMinusToken), visitTypeNode(node.type)); - case 192 /* LiteralType */: - ts.Debug.type(node); - return ts.factory.updateLiteralTypeNode(node, visitExpression(node.literal, ts.isLiteralTypeLikeExpression)); - case 194 /* TemplateLiteralType */: - ts.Debug.type(node); - return ts.factory.updateTemplateLiteralType(node, visit(node.head, ts.isTemplateHead), visitList(node.templateSpans, ts.isTemplateLiteralTypeSpan)); - case 195 /* TemplateLiteralTypeSpan */: - ts.Debug.type(node); - return ts.factory.updateTemplateLiteralTypeSpan(node, visitTypeNode(node.type), visit(node.literal, ts.isTemplateMiddleOrTemplateTail)); - // Binding patterns - case 197 /* ObjectBindingPattern */: - ts.Debug.type(node); - return ts.factory.updateObjectBindingPattern(node, visitList(node.elements, ts.isBindingElement)); - case 198 /* ArrayBindingPattern */: - ts.Debug.type(node); - return ts.factory.updateArrayBindingPattern(node, visitList(node.elements, ts.isArrayBindingElement)); - case 199 /* BindingElement */: - ts.Debug.type(node); - return ts.factory.updateBindingElement(node, visit(node.dotDotDotToken, ts.isDotDotDotToken), visitPropertyName(node.propertyName), visitBindingName(node.name), visitExpression(node.initializer)); - // Misc - case 229 /* TemplateSpan */: - ts.Debug.type(node); - return ts.factory.updateTemplateSpan(node, visitExpression(node.expression), visit(node.literal, ts.isTemplateMiddleOrTemplateTail)); - // Element - case 231 /* Block */: - ts.Debug.type(node); - return ts.factory.updateBlock(node, visitList(node.statements, ts.isStatement)); - case 233 /* VariableStatement */: - ts.Debug.type(node); - return ts.factory.updateVariableStatement(node, visitList(node.modifiers, ts.isModifier), visit(node.declarationList, ts.isVariableDeclarationList)); - case 234 /* ExpressionStatement */: - ts.Debug.type(node); - return ts.factory.updateExpressionStatement(node, visitExpression(node.expression)); - case 235 /* IfStatement */: - ts.Debug.type(node); - return ts.factory.updateIfStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.thenStatement), visitEmbeddedStatement(node.elseStatement)); - case 236 /* DoStatement */: - ts.Debug.type(node); - return ts.factory.updateDoStatement(node, visitEmbeddedStatement(node.statement), visitExpression(node.expression)); - case 237 /* WhileStatement */: - ts.Debug.type(node); - return ts.factory.updateWhileStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 238 /* ForStatement */: - ts.Debug.type(node); - return ts.factory.updateForStatement(node, visitForInitializer(node.initializer), visitExpression(node.condition), visitExpression(node.incrementor), visitEmbeddedStatement(node.statement)); - case 239 /* ForInStatement */: - ts.Debug.type(node); - return ts.factory.updateForInStatement(node, visitForInitializer(node.initializer), visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 240 /* ForOfStatement */: - ts.Debug.type(node); - return ts.factory.updateForOfStatement(node, visit(node.awaitModifier, ts.isAwaitKeyword), visitForInitializer(node.initializer), visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 241 /* ContinueStatement */: - ts.Debug.type(node); - return ts.factory.updateContinueStatement(node, visitIdentifierName(node.label)); - case 242 /* BreakStatement */: - ts.Debug.type(node); - return ts.factory.updateBreakStatement(node, visitIdentifierName(node.label)); - case 243 /* ReturnStatement */: - ts.Debug.type(node); - return ts.factory.updateReturnStatement(node, visitExpression(node.expression)); - case 244 /* WithStatement */: - ts.Debug.type(node); - return ts.factory.updateWithStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 245 /* SwitchStatement */: - ts.Debug.type(node); - return ts.factory.updateSwitchStatement(node, visitExpression(node.expression), visit(node.caseBlock, ts.isCaseBlock)); - case 246 /* LabeledStatement */: - ts.Debug.type(node); - return ts.factory.updateLabeledStatement(node, visitIdentifierName(node.label), visitEmbeddedStatement(node.statement)); - case 247 /* ThrowStatement */: - ts.Debug.type(node); - return ts.factory.updateThrowStatement(node, visitExpression(node.expression)); - case 248 /* TryStatement */: - ts.Debug.type(node); - return ts.factory.updateTryStatement(node, visit(node.tryBlock, ts.isBlock), visit(node.catchClause, ts.isCatchClause), visit(node.finallyBlock, ts.isBlock)); - // Declarations - case 250 /* VariableDeclaration */: - ts.Debug.type(node); - return ts.factory.updateVariableDeclaration(node, visitBindingName(node.name), visit(node.exclamationToken, ts.isExclamationToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 251 /* VariableDeclarationList */: - ts.Debug.type(node); - return ts.factory.updateVariableDeclarationList(node, visitList(node.declarations, ts.isVariableDeclaration)); - case 252 /* FunctionDeclaration */: - ts.Debug.type(node); - return ts.factory.updateFunctionDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 253 /* ClassDeclaration */: - ts.Debug.type(node); - return ts.factory.updateClassDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isClassElement)); - case 254 /* InterfaceDeclaration */: - ts.Debug.type(node); - return ts.factory.updateInterfaceDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isTypeElement)); - case 255 /* TypeAliasDeclaration */: - ts.Debug.type(node); - return ts.factory.updateTypeAliasDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitTypeNode(node.type)); - case 256 /* EnumDeclaration */: - ts.Debug.type(node); - return ts.factory.updateEnumDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.members, ts.isEnumMember)); - case 257 /* ModuleDeclaration */: - ts.Debug.type(node); - return ts.factory.updateModuleDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitModuleName(node.name), visit(node.body, ts.isModuleBody)); - case 258 /* ModuleBlock */: - ts.Debug.type(node); - return ts.factory.updateModuleBlock(node, visitList(node.statements, ts.isStatement)); - case 259 /* CaseBlock */: - ts.Debug.type(node); - return ts.factory.updateCaseBlock(node, visitList(node.clauses, ts.isCaseOrDefaultClause)); - case 260 /* NamespaceExportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateNamespaceExportDeclaration(node, visitIdentifierName(node.name)); - case 261 /* ImportEqualsDeclaration */: - ts.Debug.type(node); - return ts.factory.updateImportEqualsDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), node.isTypeOnly, visitIdentifierName(node.name), visit(node.moduleReference, ts.isModuleReference)); - case 262 /* ImportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateImportDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.importClause, ts.isImportClause), visitExpression(node.moduleSpecifier)); - case 263 /* ImportClause */: - ts.Debug.type(node); - return ts.factory.updateImportClause(node, node.isTypeOnly, visitIdentifierName(node.name), visit(node.namedBindings, ts.isNamedImportBindings)); - case 264 /* NamespaceImport */: - ts.Debug.type(node); - return ts.factory.updateNamespaceImport(node, visitIdentifierName(node.name)); - case 270 /* NamespaceExport */: - ts.Debug.type(node); - return ts.factory.updateNamespaceExport(node, visitIdentifierName(node.name)); - case 265 /* NamedImports */: - ts.Debug.type(node); - return ts.factory.updateNamedImports(node, visitList(node.elements, ts.isImportSpecifier)); - case 266 /* ImportSpecifier */: - ts.Debug.type(node); - return ts.factory.updateImportSpecifier(node, visitIdentifierName(node.propertyName), visitIdentifierName(node.name)); - case 267 /* ExportAssignment */: - ts.Debug.type(node); - return ts.factory.updateExportAssignment(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitExpression(node.expression)); - case 268 /* ExportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateExportDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), node.isTypeOnly, visit(node.exportClause, ts.isNamedExportBindings), visitExpression(node.moduleSpecifier)); - case 269 /* NamedExports */: - ts.Debug.type(node); - return ts.factory.updateNamedExports(node, visitList(node.elements, ts.isExportSpecifier)); - case 271 /* ExportSpecifier */: - ts.Debug.type(node); - return ts.factory.updateExportSpecifier(node, visitIdentifierName(node.propertyName), visitIdentifierName(node.name)); - case 272 /* MissingDeclaration */: - return node; - // Module references - case 273 /* ExternalModuleReference */: - ts.Debug.type(node); - return ts.factory.updateExternalModuleReference(node, visitExpression(node.expression)); - // JSX (non-expression) - case 276 /* JsxOpeningElement */: - ts.Debug.type(node); - return ts.factory.updateJsxOpeningElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression), visitList(node.typeArguments, ts.isTypeNode), visit(node.attributes, ts.isJsxAttributes)); - case 277 /* JsxClosingElement */: - ts.Debug.type(node); - return ts.factory.updateJsxClosingElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression)); - case 281 /* JsxAttribute */: - ts.Debug.type(node); - return ts.factory.updateJsxAttribute(node, visitIdentifierName(node.name), visitJsxAttributeValue(node.initializer)); - case 282 /* JsxAttributes */: - ts.Debug.type(node); - return ts.factory.updateJsxAttributes(node, visitList(node.properties, ts.isJsxAttributeLike)); - case 283 /* JsxSpreadAttribute */: - ts.Debug.type(node); - return ts.factory.updateJsxSpreadAttribute(node, visitExpression(node.expression)); - case 284 /* JsxExpression */: - ts.Debug.type(node); - return ts.factory.updateJsxExpression(node, visitExpression(node.expression)); - // Clauses - case 285 /* CaseClause */: - ts.Debug.type(node); - return ts.factory.updateCaseClause(node, visitExpression(node.expression), visitList(node.statements, ts.isStatement)); - case 286 /* DefaultClause */: - ts.Debug.type(node); - return ts.factory.updateDefaultClause(node, visitList(node.statements, ts.isStatement)); - case 287 /* HeritageClause */: - ts.Debug.type(node); - return ts.factory.updateHeritageClause(node, visitList(node.types, ts.isExpressionWithTypeArguments)); - case 288 /* CatchClause */: - ts.Debug.type(node); - return ts.factory.updateCatchClause(node, visit(node.variableDeclaration, ts.isVariableDeclaration), visit(node.block, ts.isBlock)); - // Property assignments - case 289 /* PropertyAssignment */: - ts.Debug.type(node); - return ts.factory.updatePropertyAssignment(node, visitPropertyName(node.name), visitExpression(node.initializer)); - case 290 /* ShorthandPropertyAssignment */: - ts.Debug.type(node); - return ts.factory.updateShorthandPropertyAssignment(node, visitIdentifierName(node.name, ts.isIdentifier), visitExpression(node.objectAssignmentInitializer)); - case 291 /* SpreadAssignment */: - ts.Debug.type(node); - return ts.factory.updateSpreadAssignment(node, visitExpression(node.expression)); - // Enum - case 292 /* EnumMember */: - ts.Debug.type(node); - return ts.factory.updateEnumMember(node, visitPropertyName(node.name), visitExpression(node.initializer)); - // JSDoc nodes (only used in codefixes currently) - case 302 /* JSDocTypeExpression */: - case 303 /* JSDocNameReference */: - case 304 /* JSDocAllType */: - case 305 /* JSDocUnknownType */: - case 306 /* JSDocNullableType */: - case 307 /* JSDocNonNullableType */: - case 308 /* JSDocOptionalType */: - case 309 /* JSDocFunctionType */: - case 310 /* JSDocVariadicType */: - case 311 /* JSDocNamepathType */: - case 312 /* JSDocComment */: - case 314 /* JSDocTypeLiteral */: - case 315 /* JSDocSignature */: - case 317 /* JSDocTag */: - case 318 /* JSDocAugmentsTag */: - case 319 /* JSDocImplementsTag */: - case 320 /* JSDocAuthorTag */: - case 321 /* JSDocDeprecatedTag */: - case 322 /* JSDocClassTag */: - case 323 /* JSDocPublicTag */: - case 324 /* JSDocPrivateTag */: - case 325 /* JSDocProtectedTag */: - case 326 /* JSDocReadonlyTag */: - case 328 /* JSDocCallbackTag */: - case 329 /* JSDocEnumTag */: - case 330 /* JSDocParameterTag */: - case 337 /* JSDocPropertyTag */: - case 331 /* JSDocReturnTag */: - case 332 /* JSDocThisTag */: - case 333 /* JSDocTypeTag */: - case 334 /* JSDocTemplateTag */: - case 335 /* JSDocTypedefTag */: - case 336 /* JSDocSeeTag */: - return node; - // Transformation nodes (ignored) - } - if (ts.isExpression(node)) { - // If this was an expression that was originally in an `Unspecified` hint, - // re-trigger substitution using the correct hint. - hint = 1 /* Expression */; - if (substituteNode !== ts.noEmitSubstitution) { - node = substituteNode(hint, node); - } - } - else if (ts.isSourceFile(node)) { - return preprintSourceFile(node); - } - } - if (hint === 1 /* Expression */) { - switch (node.kind) { - // Identifiers - case 78 /* Identifier */: - return preprintIdentifier(node); - // Expression - case 200 /* ArrayLiteralExpression */: - ts.Debug.type(node); - return ts.factory.updateArrayLiteralExpression(node, visitExpressionList(node.elements)); - case 201 /* ObjectLiteralExpression */: - ts.Debug.type(node); - return ts.factory.updateObjectLiteralExpression(node, visitList(node.properties, ts.isObjectLiteralElementLike)); - case 202 /* PropertyAccessExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updatePropertyAccessChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitMemberName(node.name)); - } - ts.Debug.type(node); - return ts.factory.updatePropertyAccessExpression(node, visitExpression(node.expression), visitMemberName(node.name)); - case 203 /* ElementAccessExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateElementAccessChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitExpression(node.argumentExpression)); - } - ts.Debug.type(node); - return ts.factory.updateElementAccessExpression(node, visitExpression(node.expression), visitExpression(node.argumentExpression)); - case 204 /* CallExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateCallChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - } - ts.Debug.type(node); - return ts.factory.updateCallExpression(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - case 205 /* NewExpression */: - ts.Debug.type(node); - return ts.factory.updateNewExpression(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - case 206 /* TaggedTemplateExpression */: - ts.Debug.type(node); - return ts.factory.updateTaggedTemplateExpression(node, visitExpression(node.tag), visitTypeNodeList(node.typeArguments), visitExpression(node.template, ts.isTemplateLiteral)); - case 207 /* TypeAssertionExpression */: - ts.Debug.type(node); - return ts.factory.updateTypeAssertion(node, visitTypeNode(node.type), visitExpression(node.expression)); - case 208 /* ParenthesizedExpression */: - ts.Debug.type(node); - return ts.factory.updateParenthesizedExpression(node, visitExpression(node.expression)); - case 209 /* FunctionExpression */: - ts.Debug.type(node); - return ts.factory.updateFunctionExpression(node, visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 210 /* ArrowFunction */: - ts.Debug.type(node); - return ts.factory.updateArrowFunction(node, visitList(node.modifiers, ts.isModifier), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visit(node.equalsGreaterThanToken, ts.isEqualsGreaterThanToken), visitConciseBody(node.body)); - case 211 /* DeleteExpression */: - ts.Debug.type(node); - return ts.factory.updateDeleteExpression(node, visitExpression(node.expression)); - case 212 /* TypeOfExpression */: - ts.Debug.type(node); - return ts.factory.updateTypeOfExpression(node, visitExpression(node.expression)); - case 213 /* VoidExpression */: - ts.Debug.type(node); - return ts.factory.updateVoidExpression(node, visitExpression(node.expression)); - case 214 /* AwaitExpression */: - ts.Debug.type(node); - return ts.factory.updateAwaitExpression(node, visitExpression(node.expression)); - case 215 /* PrefixUnaryExpression */: - ts.Debug.type(node); - return ts.factory.updatePrefixUnaryExpression(node, visitExpression(node.operand)); - case 216 /* PostfixUnaryExpression */: - ts.Debug.type(node); - return ts.factory.updatePostfixUnaryExpression(node, visitExpression(node.operand)); - case 217 /* BinaryExpression */: - return preprintBinaryExpression(node); - case 218 /* ConditionalExpression */: - ts.Debug.type(node); - return ts.factory.updateConditionalExpression(node, visitExpression(node.condition), visit(node.questionToken, ts.isQuestionToken), visitExpression(node.whenTrue), visit(node.colonToken, ts.isColonToken), visitExpression(node.whenFalse)); - case 219 /* TemplateExpression */: - ts.Debug.type(node); - return ts.factory.updateTemplateExpression(node, visit(node.head, ts.isTemplateHead), visitList(node.templateSpans, ts.isTemplateSpan)); - case 220 /* YieldExpression */: - ts.Debug.type(node); - return ts.factory.updateYieldExpression(node, visit(node.asteriskToken, ts.isAsteriskToken), visitExpression(node.expression)); - case 221 /* SpreadElement */: - ts.Debug.type(node); - return ts.factory.updateSpreadElement(node, visitExpression(node.expression)); - case 222 /* ClassExpression */: - ts.Debug.type(node); - return ts.factory.updateClassExpression(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isClassElement)); - case 225 /* AsExpression */: - ts.Debug.type(node); - return ts.factory.updateAsExpression(node, visitExpression(node.expression), visitTypeNode(node.type)); - case 226 /* NonNullExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateNonNullChain(node, visitExpression(node.expression)); - } - ts.Debug.type(node); - return ts.factory.updateNonNullExpression(node, visitExpression(node.expression)); - case 227 /* MetaProperty */: - ts.Debug.type(node); - return ts.factory.updateMetaProperty(node, visitIdentifierName(node.name)); - // JSX (expression only) - case 274 /* JsxElement */: - ts.Debug.type(node); - return ts.factory.updateJsxElement(node, visit(node.openingElement, ts.isJsxOpeningElement), visitList(node.children, ts.isJsxChild), visit(node.closingElement, ts.isJsxClosingElement)); - case 275 /* JsxSelfClosingElement */: - ts.Debug.type(node); - return ts.factory.updateJsxSelfClosingElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression), visitList(node.typeArguments, ts.isTypeNode), visit(node.attributes, ts.isJsxAttributes)); - case 278 /* JsxFragment */: - ts.Debug.type(node); - return ts.factory.updateJsxFragment(node, visit(node.openingFragment, ts.isJsxOpeningFragment), visitList(node.children, ts.isJsxChild), visit(node.closingFragment, ts.isJsxClosingFragment)); - // Transformation nodes - case 340 /* PartiallyEmittedExpression */: - ts.Debug.type(node); - return ts.factory.updatePartiallyEmittedExpression(node, visitExpression(node.expression)); - case 341 /* CommaListExpression */: - ts.Debug.type(node); - return ts.factory.updateCommaListExpression(node, visitExpressionList(node.elements, ts.isExpression)); - } - } - if (ts.Debug.shouldAssert(1 /* Normal */)) { - // Any other node should not have children or this list isn't up to date. - ts.Debug.assertMissingNode(ts.forEachChild(node, ts.identity), "Expected " + ts.Debug.formatSyntaxKind(node.kind) + " to contain no children."); - } - // No need to visit nodes with no children. - return node; - } - function preprintSourceFile(node) { - return ts.factory.updateSourceFile(node, visitList(node.statements, ts.isStatement)); - } - function preprintIdentifier(node) { - return ts.factory.updateIdentifier(node, visitList(node.typeArguments, ts.isTypeNodeOrTypeParameterDeclaration)); - } - function preprintTypeParameterDeclaration(node) { - return ts.factory.updateTypeParameterDeclaration(node, visitIdentifierName(node.name), visitTypeNode(node.constraint), visitTypeNode(node.default)); - } - function createPreprintBinaryExpression() { - return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); - function onEnter(node, state) { - if (state) { - state.stackIndex++; - state.leftStack[state.stackIndex] = node.left; - state.operatorStack[state.stackIndex] = node.operatorToken; - state.rightStack[state.stackIndex] = node.right; - } - else { - state = { - stackIndex: 0, - leftStack: [node.left], - operatorStack: [node.operatorToken], - rightStack: [node.right], - }; - } - return state; - } - function onLeft(left, state, _node) { - return maybeVisitExpression(left, state, "left"); - } - function onOperator(operator, state, _node) { - state.operatorStack[state.stackIndex] = visit(operator, ts.isBinaryOperatorToken); - } - function onRight(right, state, _node) { - return maybeVisitExpression(right, state, "right"); - } - function onExit(node, state) { - var left = state.leftStack[state.stackIndex]; - var operator = state.operatorStack[state.stackIndex]; - var right = state.rightStack[state.stackIndex]; - if (state.stackIndex > 0) { - state.stackIndex--; - } - return ts.factory.updateBinaryExpression(node, left, operator, right); - } - function foldState(state, result, side) { - (side === "left" ? state.leftStack : state.rightStack)[state.stackIndex] = result; - return state; - } - function maybeVisitExpression(node, state, side) { - // Get the first supported pipeline phase for this node. We can skip several stack - // frames if we aren't doing emit notification, so we check for substitution and - // direct callbacks and execute those immediately. - var pipelinePhase = getPipelinePhase(0 /* Notification */, node); - if (pipelinePhase === pipelineVisitWithSubstitution) { - // The next phase after substitution is always direct visitation, so we can reduce the call stack - // depth by proceding to the direct visitor. - node = ts.cast(substituteNode(1 /* Expression */, node), ts.isExpression); - pipelinePhase = pipelineVisitDirect; - } - if (pipelinePhase === pipelineVisitDirect && ts.isBinaryExpression(node)) { - // If we are visiting directly and the next node is a BinaryExpression, we can - // add it to the stack and continue the trampoline. - return node; - } - else { - // Visit the expression and store the result on whichever side we are currently visiting. - (side === "left" ? state.leftStack : state.rightStack)[state.stackIndex] = visitExpression(node, ts.isExpression); - } - } - } - var preprintBinaryExpression = createPreprintBinaryExpression(); - function preprint(hint, node) { - // If we're not performing substitution or notification, we have no work to do here. - if (substituteNode === ts.noEmitSubstitution && - onEmitNode === ts.noEmitNotification) { - return node; - } - switch (hint) { - case 0 /* SourceFile */: return visitSourceFile(ts.cast(node, ts.isSourceFile)); - case 1 /* Expression */: return visitExpression(ts.cast(node, ts.isExpression)); - case 2 /* IdentifierName */: return visitIdentifierName(ts.cast(node, ts.isIdentifier)); - case 3 /* MappedTypeParameter */: return visitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 5 /* EmbeddedStatement */: return visitEmbeddedStatement(ts.cast(node, ts.isStatement)); - case 6 /* JsxAttributeValue */: return visitJsxAttributeValue(ts.cast(node, ts.isStringLiteralOrJsxExpression)); - default: return visit(node); - } - } - return preprint; - } function createBracketsMap() { var brackets = []; brackets[1024 /* Braces */] = ["{", "}"]; @@ -109434,6 +109370,7 @@ var ts; var hasEmitBlockingDiagnostics = new ts.Map(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; + var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { @@ -109448,7 +109385,7 @@ var ts; }); }; } else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } @@ -109457,7 +109394,8 @@ var ts; actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { - var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; // TODO: GH#18217 actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -109614,6 +109552,7 @@ var ts; } }); } + typeReferenceDirectiveResolutionCache = undefined; // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; var program = { @@ -109807,13 +109746,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_15 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_14.push(resolvedModule); + result_15.push(resolvedModule); } - return result_14; + return result_15; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -111245,12 +111184,14 @@ var ts; return host.getCanonicalFileName(fileName); } function processImportedModules(file) { + var _a; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var resolutions = resolveModuleNamesReusingOldState(moduleNames, file); ts.Debug.assert(resolutions.length === moduleNames.length); + var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options; for (var index = 0; index < moduleNames.length; index++) { var resolution = resolutions[index]; ts.setResolvedModule(file, moduleNames[index], resolution); @@ -111273,11 +111214,11 @@ var ts; // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !ts.getAllowJSCompilerOption(options)) + && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile)) && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -112365,7 +112306,7 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos: fileInfos, @@ -113165,7 +113106,16 @@ var ts; var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - return signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; + var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); var referencedMap; if (state.referencedMap) { @@ -113214,7 +113164,7 @@ var ts; return { fileNames: fileNames, fileInfos: fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, @@ -113246,17 +113196,16 @@ var ts; return fileIdListId; } } - function convertToReusableCompilerOptions(options, relativeToBuildInfo) { - var result = {}; + function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { + var result; var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo); + 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.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { @@ -113572,6 +113521,14 @@ var ts; state.affectedFilesPendingEmitIndex = 0; } } + function toBuilderStateFileInfo(fileInfo) { + return ts.isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + ts.isString(fileInfo.signature) ? + fileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; + } + ts.toBuilderStateFileInfo = toBuilderStateFileInfo; function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { var _a; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); @@ -113579,10 +113536,10 @@ var ts; 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), fileInfo); }); + program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); var state = { fileInfos: fileInfos, - compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, referencedMap: toMapOfReferencedSet(program.referencedMap), exportedModulesMap: toMapOfReferencedSet(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]; }), @@ -113742,9 +113699,9 @@ var ts; var resolutionsWithFailedLookups = []; var resolvedFileToResolution = ts.createMultiMap(); var hasChangedAutomaticTypeDirectiveNames = false; - var failedLookupChecks = []; - var startsWithPathChecks = []; - var isInDirectoryChecks = []; + var failedLookupChecks; + var startsWithPathChecks; + var isInDirectoryChecks; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -113753,9 +113710,12 @@ var ts; var resolvedModuleNames = new ts.Map(); var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache); var resolvedTypeReferenceDirectives = new ts.Map(); var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -113813,9 +113773,9 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.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(); @@ -113851,9 +113811,8 @@ var ts; isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -113880,7 +113839,7 @@ 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), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; @@ -113891,6 +113850,9 @@ var ts; // Default return the result from the first pass return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } function resolveNamesWithLocalCache(_a) { var _b; var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; @@ -113978,7 +113940,7 @@ var ts; redirectedReference: redirectedReference, cache: resolvedTypeReferenceDirectives, perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, - loader: ts.resolveTypeReferenceDirective, + loader: resolveTypeReferenceDirective, getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, }); @@ -114253,7 +114215,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -114271,8 +114233,8 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -114283,27 +114245,33 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(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. + var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { return resolution.failedLookupLocations.some(function (location) { var locationPath = resolutionHost.toPath(location); return ts.contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) || - isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, 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); })); }); } function closeTypeRootsWatch() { @@ -114524,7 +114492,7 @@ var ts; if (!baseUrl && !paths || relativePreference === 0 /* Relative */) { return relativePath; } - var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl; + var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -114539,7 +114507,9 @@ var ts; return nonRelative; } if (relativePreference === 3 /* ExternalNonRelative */) { - var projectDirectory = host.getCurrentDirectory(); + var projectDirectory = compilerOptions.configFilePath ? + ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName); var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory); var targetIsInternal = ts.startsWith(modulePath, projectDirectory); @@ -114614,9 +114584,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 links = host.getSymlinkCache ? host.getSymlinkCache() @@ -114639,10 +114609,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; } }); }); @@ -114773,7 +114743,7 @@ var ts; ts.startsWith(relativeToBaseUrl, prefix) && ts.endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } @@ -116374,12 +116344,19 @@ var ts; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); 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) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } + if (!compilerHost.resolveTypeReferenceDirectives) { + var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4); + }; + } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -116404,6 +116381,7 @@ var ts; projectErrorsReported: new ts.Map(), compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, + typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, // Mutable state buildOrder: undefined, readFileWithCache: function (f) { return host.readFile(f); }, @@ -116591,7 +116569,7 @@ var ts; function disableCache(state) { if (!state.cache) return; - var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache; + var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -116600,10 +116578,8 @@ var ts; compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear(); state.cache = undefined; } function clearProjectStatus(state, resolved) { @@ -116770,6 +116746,7 @@ var ts; return withProgramOrUndefined(action) || ts.emptyArray; } function createProgram() { + var _a, _b; ts.Debug.assert(program === undefined); if (state.options.dry) { reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -116789,7 +116766,8 @@ var ts; var host = state.host, compilerHost = state.compilerHost; state.projectCompilerOptions = config.options; // Update module resolution cache if needed - updateModuleResolutionCache(state, project, config); + (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { @@ -116964,7 +116942,7 @@ var ts; emitBundle(writeFile, customTransformers); break; case BuildStep.BuildInvalidatedProjectOfBundle: - ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; case BuildStep.QueueReferencingProjects: @@ -117106,31 +117084,6 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache(state, proj, config) { - if (!state.moduleResolutionCache) - return; - // Update module resolution cache if needed - var moduleResolutionCache = state.moduleResolutionCache; - var projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - // The own map will be for projectCompilerOptions - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - // Set correct own map - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - var ref = { - sourceFile: config.options.configFile, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time var tsconfigTime = ts.getModifiedTime(state.host, configFile); @@ -117143,6 +117096,7 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { + var force = !!state.options.force; var newestInputFileName = undefined; var newestInputFileTime = minimumDate; var host = state.host; @@ -117155,11 +117109,13 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = ts.getModifiedTime(host, inputFile); - host.getModifiedTime(inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + var inputTime = ts.getModifiedTime(host, inputFile); + host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } // Container if no files are specified in the project @@ -117178,36 +117134,38 @@ var ts; var missingOutputFileName; var newestDeclarationFileContentChangedTime = minimumDate; var isOutOfDateWithInputs = false; - 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 (isDeclarationFile(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + 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 (isDeclarationFile(output)) { + var outputModifiedTime = ts.getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } var pseudoUpToDate = false; @@ -117243,7 +117201,8 @@ var ts; }; } // Check oldest output file name only if there is no missing output file name - if (!missingOutputFileName) { + // (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) { @@ -117289,7 +117248,7 @@ var ts; if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -117431,7 +117390,7 @@ var ts; } } } - function build(state, project, cancellationToken, onlyReferences) { + function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -117443,7 +117402,7 @@ var ts; if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -117625,9 +117584,9 @@ var ts; function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: function (project, cancellationToken) { return build(state, project, cancellationToken); }, + build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); }, clean: function (project) { return clean(state, project); }, - buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); }, + buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, /*onlyReferences*/ true); }, cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); }, getNextInvalidatedProject: function (cancellationToken) { setupInitialBuild(state, cancellationToken); @@ -117717,6 +117676,9 @@ 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)); @@ -118856,7 +118818,7 @@ var ts; case 167 /* Constructor */: return "constructor" /* constructorImplementationElement */; case 160 /* TypeParameter */: return "type parameter" /* typeParameterElement */; case 292 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 161 /* Parameter */: return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 161 /* Parameter */: return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; case 261 /* ImportEqualsDeclaration */: case 266 /* ImportSpecifier */: case 271 /* ExportSpecifier */: @@ -119540,6 +119502,21 @@ var ts; return current; } } + /** + * Returns the first token where position is in [start, end), + * excluding `JsxText` tokens containing only whitespace. + */ + function findFirstNonJsxWhitespaceToken(sourceFile, position) { + var tokenAtPosition = getTokenAtPosition(sourceFile, position); + while (isWhiteSpaceOnlyJsxText(tokenAtPosition)) { + var nextToken = findNextToken(tokenAtPosition, tokenAtPosition.parent, sourceFile); + if (!nextToken) + return; + tokenAtPosition = nextToken; + } + return tokenAtPosition; + } + ts.findFirstNonJsxWhitespaceToken = findFirstNonJsxWhitespaceToken; /** * The token on the left of the position is the token that strictly includes the position * or sits to the left of the cursor if it is on a boundary. For example @@ -120534,6 +120511,14 @@ var ts; return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); } ts.operatorPart = operatorPart; + function parameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.parameterName); + } + ts.parameterNamePart = parameterNamePart; + function propertyNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.propertyName); + } + ts.propertyNamePart = propertyNamePart; function textOrKeywordPart(text) { var kind = ts.stringToToken(text); return kind === undefined @@ -120545,6 +120530,14 @@ var ts; return displayPart(text, ts.SymbolDisplayPartKind.text); } ts.textPart = textPart; + function typeAliasNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.aliasName); + } + ts.typeAliasNamePart = typeAliasNamePart; + function typeParameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.typeParameterName); + } + ts.typeParameterNamePart = typeParameterNamePart; function linkTextPart(text) { return displayPart(text, ts.SymbolDisplayPartKind.linkText); } @@ -120565,6 +120558,7 @@ var ts; } ts.linkPart = linkPart; function buildLinkParts(link, checker) { + var _a; var parts = [linkPart("{@link ")]; if (!link.name) { if (link.text) { @@ -120573,8 +120567,9 @@ var ts; } else { var symbol = checker === null || checker === void 0 ? void 0 : checker.getSymbolAtLocation(link.name); - if (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) { - parts.push(linkNamePart(link.name, symbol.valueDeclaration)); + var decl = (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) || ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]); + if (decl) { + parts.push(linkNamePart(link.name, decl)); if (link.text) { parts.push(linkTextPart(link.text)); } @@ -123854,6 +123849,7 @@ var ts; sourceDisplay: sourceDisplay, isSnippet: isSnippet, isPackageJsonImport: originIsPackageJsonImport(origin) || undefined, + isImportStatementCompletion: originIsResolvedExport(origin) || undefined, data: data, }; } @@ -124655,7 +124651,8 @@ var ts; return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined; } function tryGetGlobalSymbols() { - var result = tryGetObjectLikeCompletionSymbols() + var result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() + || tryGetObjectLikeCompletionSymbols() || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() @@ -124800,8 +124797,9 @@ var ts; } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 111 /* TypeOfKeyword */ && - (contextToken.parent.kind === 177 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + ((contextToken.kind === 111 /* TypeOfKeyword */ && + (contextToken.parent.kind === 177 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent))) || + (contextToken.kind === 127 /* AssertsKeyword */ && contextToken.parent.kind === 173 /* TypePredicate */)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { @@ -125018,6 +125016,25 @@ var ts; return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) || position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken))); } + function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() { + var typeLiteralNode = tryGetTypeLiteralNode(contextToken); + if (!typeLiteralNode) + return 0 /* Continue */; + var intersectionTypeNode = ts.isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : undefined; + var containerTypeNode = intersectionTypeNode || typeLiteralNode; + var containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker); + if (!containerExpectedType) + return 0 /* Continue */; + var containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode); + var members = getPropertiesForCompletion(containerExpectedType, typeChecker); + var existingMembers = getPropertiesForCompletion(containerActualType, typeChecker); + var existingMemberEscapedNames = new ts.Set(); + existingMembers.forEach(function (s) { return existingMemberEscapedNames.add(s.escapedName); }); + symbols = ts.filter(members, function (s) { return !existingMemberEscapedNames.has(s.escapedName); }); + completionKind = 0 /* ObjectPropertyDeclaration */; + isNewIdentifierLocation = true; + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in object literals and object binding patterns. * Relevant symbols are stored in the captured 'symbols' variable. @@ -125402,7 +125419,7 @@ var ts; case 41 /* AsteriskToken */: return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } - // If the previous token is keyword correspoding to class member completion keyword + // If the previous token is keyword corresponding to class member completion keyword // there will be completion available here if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; @@ -125437,6 +125454,31 @@ var ts; case 129 /* AsyncKeyword */: return ts.isPropertyDeclaration(contextToken.parent); } + // If we are inside a class declaration, and `constructor` is totally not present, + // but we request a completion manually at a whitespace... + var ancestorClassLike = ts.findAncestor(contextToken.parent, ts.isClassLike); + if (ancestorClassLike && contextToken === previousToken && isPreviousPropertyDeclarationTerminated(contextToken, position)) { + return false; // Don't block completions. + } + var ancestorPropertyDeclaraion = ts.getAncestor(contextToken.parent, 164 /* PropertyDeclaration */); + // If we are inside a class declaration and typing `constructor` after property declaration... + if (ancestorPropertyDeclaraion + && contextToken !== previousToken + && ts.isClassLike(previousToken.parent.parent) + // And the cursor is at the token... + && position <= previousToken.end) { + // If we are sure that the previous property declaration is terminated according to newline or semicolon... + if (isPreviousPropertyDeclarationTerminated(contextToken, previousToken.end)) { + return false; // Don't block completions. + } + else if (contextToken.kind !== 62 /* EqualsToken */ + // Should not block: `class C { blah = c/**/ }` + // But should block: `class C { blah = somewhat c/**/ }` and `class C { blah: SomeType c/**/ }` + && (ts.isInitializedProperty(ancestorPropertyDeclaraion) + || ts.hasType(ancestorPropertyDeclaraion))) { + return true; + } + } return ts.isDeclarationName(contextToken) && !ts.isShorthandPropertyAssignment(contextToken.parent) && !ts.isJsxAttribute(contextToken.parent) @@ -125444,6 +125486,11 @@ var ts; // If `contextToken !== previousToken`, this is `class C ex/**/`. && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } + function isPreviousPropertyDeclarationTerminated(contextToken, position) { + return contextToken.kind !== 62 /* EqualsToken */ && + (contextToken.kind === 26 /* SemicolonToken */ + || !ts.positionsAreOnSameLine(contextToken.end, position, sourceFile)); + } function isFunctionLikeButNotConstructor(kind) { return ts.isFunctionLikeKind(kind) && kind !== 167 /* Constructor */; } @@ -125849,6 +125896,12 @@ var ts; } if (!contextToken) return undefined; + // class C { blah; constructor/**/ } and so on + if (location.kind === 132 /* ConstructorKeyword */ + // class C { blah \n constructor/**/ } + || (ts.isIdentifier(contextToken) && ts.isPropertyDeclaration(contextToken.parent) && ts.isClassLike(location))) { + return ts.findAncestor(contextToken, ts.isClassLike); + } switch (contextToken.kind) { case 62 /* EqualsToken */: return undefined; @@ -125874,6 +125927,44 @@ var ts; ? contextToken.parent.parent : undefined; } } + function tryGetTypeLiteralNode(node) { + if (!node) + return undefined; + var parent = node.parent; + switch (node.kind) { + case 18 /* OpenBraceToken */: + if (ts.isTypeLiteralNode(parent)) { + return parent; + } + break; + case 26 /* SemicolonToken */: + case 27 /* CommaToken */: + case 78 /* Identifier */: + if (parent.kind === 163 /* PropertySignature */ && ts.isTypeLiteralNode(parent.parent)) { + return parent.parent; + } + break; + } + return undefined; + } + function getConstraintOfTypeArgumentProperty(node, checker) { + if (!node) + return undefined; + if (ts.isTypeNode(node) && ts.isTypeReferenceType(node.parent)) { + return checker.getTypeArgumentConstraint(node); + } + var t = getConstraintOfTypeArgumentProperty(node.parent, checker); + if (!t) + return undefined; + switch (node.kind) { + case 163 /* PropertySignature */: + return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); + case 184 /* IntersectionType */: + case 178 /* TypeLiteral */: + case 183 /* UnionType */: + return t; + } + } // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes function isFromObjectTypeDeclaration(node) { return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); @@ -125933,7 +126024,8 @@ var ts; if (type) { return type; } - if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { + if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ && node === node.parent.left) { + // Object literal is assignment pattern: ({ | } = x) return typeChecker.getTypeAtLocation(node.parent); } return undefined; @@ -126434,6 +126526,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function isDocumentRegistryEntry(entry) { + return !!entry.sourceFile; + } function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); } @@ -126450,10 +126545,16 @@ var ts; var entries = buckets.get(name); var sourceFiles = []; entries.forEach(function (entry, name) { - sourceFiles.push({ - name: name, - refCount: entry.languageServiceRefCount - }); + if (isDocumentRegistryEntry(entry)) { + sourceFiles.push({ + name: name, + scriptKind: entry.sourceFile.scriptKind, + refCount: entry.languageServiceRefCount + }); + } + else { + entry.forEach(function (value, scriptKind) { return sourceFiles.push({ name: name, scriptKind: scriptKind, refCount: value.languageServiceRefCount }); }); + } }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); return { @@ -126479,10 +126580,17 @@ var ts; function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } + 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:" + scriptKind + " and sourceFile.scriptKind: " + (entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind) + ", !entry: " + !entry); + return entry; + } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); - var entry = bucket.get(path); + scriptKind = ts.ensureScriptKind(fileName, scriptKind); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; + var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -126491,7 +126599,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 0 }; - bucket.set(path, entry); + setBucketEntry(); } } if (!entry) { @@ -126504,7 +126612,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 1, }; - bucket.set(path, entry); + setBucketEntry(); } else { // We have an entry for this file. However, it may be for a different version of @@ -126527,25 +126635,49 @@ var ts; } ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; + function setBucketEntry() { + if (!bucketEntry) { + bucket.set(path, entry); + } + else if (isDocumentRegistryEntry(bucketEntry)) { + var scriptKindMap = new ts.Map(); + scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry); + scriptKindMap.set(scriptKind, entry); + bucket.set(path, scriptKindMap); + } + else { + bucketEntry.set(scriptKind, entry); + } + } } - function releaseDocument(fileName, compilationSettings) { + function releaseDocument(fileName, compilationSettings, scriptKind) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); + return releaseDocumentWithKey(path, key, scriptKind); } - function releaseDocumentWithKey(path, key) { + function releaseDocumentWithKey(path, key, scriptKind) { var bucket = ts.Debug.checkDefined(buckets.get(key)); - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.delete(path); + if (isDocumentRegistryEntry(bucketEntry)) { + bucket.delete(path); + } + else { + bucketEntry.delete(scriptKind); + if (bucketEntry.size === 1) { + bucket.set(path, ts.firstDefinedIterator(bucketEntry.values(), ts.identity)); + } + } } } - function getLanguageServiceRefCounts(path) { + function getLanguageServiceRefCounts(path, scriptKind) { return ts.arrayFrom(buckets.entries(), function (_a) { var key = _a[0], bucket = _a[1]; - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); return [key, entry && entry.languageServiceRefCount]; }); } @@ -126975,13 +127107,13 @@ var ts; function getExport() { var _a; var parent = node.parent; - var grandParent = parent.parent; + var grandparent = parent.parent; if (symbol.exportSymbol) { if (parent.kind === 202 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandParent) - ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandparent) + ? getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ false) : undefined; } else { @@ -127011,15 +127143,15 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(grandParent)) { - return getExportAssignmentExport(grandParent); + else if (ts.isExportAssignment(grandparent)) { + return getExportAssignmentExport(grandparent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(grandParent)) { - return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandparent)) { + return getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ true); } else if (ts.isJSDocTypedefTag(parent)) { return exportInfo(symbol, 0 /* Named */); @@ -127027,9 +127159,10 @@ var ts; } function getExportAssignmentExport(ex) { // Get the symbol for the `export =` node; its parent is the module it's the export of. - var exportingModuleSymbol = ts.Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + if (!ex.symbol.parent) + return undefined; var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; - return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: ex.symbol.parent, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; @@ -127981,9 +128114,9 @@ var ts; // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); } - else if (node && node.kind === 87 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */) { + else if (node && node.kind === 87 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) { addReference(node, symbol, state); - searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); @@ -128198,7 +128331,9 @@ var ts; for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { var node = _d[_c]; // Import specifiers should be handled by importSearches - if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + var symbol = checker.getSymbolAtLocation(node); + var hasExportAssignmentDeclaration = ts.some(symbol === null || symbol === void 0 ? void 0 : symbol.declarations, function (d) { return ts.tryCast(d, ts.isExportAssignment) ? true : false; }); + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) { cb(node); } } @@ -128505,6 +128640,10 @@ var ts; default: ts.Debug.assertNever(state.specialSearchKind); } + // Use the parent symbol if the location is commonjs require syntax on javascript files only. + referenceSymbol = ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 199 /* BindingElement */ && ts.isRequireVariableDeclaration(referenceLocation.parent) + ? referenceLocation.parent.symbol + : referenceSymbol; getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { @@ -128872,6 +129011,8 @@ var ts; case 166 /* MethodDeclaration */: case 165 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { + staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning object literals break; } // falls through @@ -128912,7 +129053,8 @@ var ts; return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; case 222 /* ClassExpression */: case 253 /* ClassDeclaration */: - // Make sure the container belongs to the same class + case 201 /* ObjectLiteralExpression */: + // Make sure the container belongs to the same class/object literals // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getSyntacticModifierFlags(container) & 32 /* Static */) === staticFlag; case 298 /* SourceFile */: @@ -130040,7 +130182,7 @@ var ts; end: node.getEnd(), fileName: node.text }, - unverified: !!verifiedFileName, + unverified: !verifiedFileName, }; } } @@ -130193,7 +130335,38 @@ var ts; var sourceFile = name.getSourceFile(); var textSpan = ts.createTextSpanFromNode(name, sourceFile); return __assign(__assign({ fileName: sourceFile.fileName, textSpan: textSpan, kind: symbolKind, name: symbolName, containerKind: undefined, // TODO: GH#18217 - containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !checker.isDeclarationVisible(declaration) }); + containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !isDefinitionVisible(checker, declaration) }); + } + function isDefinitionVisible(checker, declaration) { + if (checker.isDeclarationVisible(declaration)) + return true; + if (!declaration.parent) + return false; + // Variable initializers are visible if variable is visible + if (ts.hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) + return isDefinitionVisible(checker, declaration.parent); + // Handle some exceptions here like arrow function, members of class and object literal expression which are technically not visible but we want the definition to be determined by its parent + switch (declaration.kind) { + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + // Private/protected properties/methods are not visible + if (ts.hasEffectiveModifier(declaration, 8 /* Private */)) + return false; + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 167 /* Constructor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + return isDefinitionVisible(checker, declaration.parent); + default: + return false; + } } function createDefinitionFromSignatureDeclaration(typeChecker, decl) { return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); @@ -130286,6 +130459,7 @@ var ts; "kind", "lends", "license", + "link", "listens", "member", "memberof", @@ -130379,8 +130553,9 @@ var ts; return ts.flatMap(comment, function (node) { return node.kind === 313 /* JSDocText */ ? [ts.textPart(node.text)] : ts.buildLinkParts(node, checker); }); } function getCommentDisplayParts(tag, checker) { - var comment = tag.comment; - switch (tag.kind) { + var comment = tag.comment, kind = tag.kind; + var namePart = getTagNameDisplayPart(kind); + switch (kind) { case 319 /* JSDocImplementsTag */: return withNode(tag.class); case 318 /* JSDocAugmentsTag */: @@ -130395,7 +130570,9 @@ var ts; case 330 /* JSDocParameterTag */: case 336 /* JSDocSeeTag */: var name = tag.name; - return name ? withNode(name) : comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); + return name ? withNode(name) + : comment === undefined ? undefined + : getDisplayPartsFromComment(comment, checker); default: return comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); } @@ -130403,7 +130580,32 @@ var ts; return addComment(node.getText()); } function addComment(s) { - return comment ? __spreadArray([ts.textPart(s), ts.spacePart()], getDisplayPartsFromComment(comment, checker)) : [ts.textPart(s)]; + if (comment) { + if (s.match(/^https?$/)) { + return __spreadArray([ts.textPart(s)], getDisplayPartsFromComment(comment, checker)); + } + else { + return __spreadArray([namePart(s), ts.spacePart()], getDisplayPartsFromComment(comment, checker)); + } + } + else { + return [ts.textPart(s)]; + } + } + } + function getTagNameDisplayPart(kind) { + switch (kind) { + case 330 /* JSDocParameterTag */: + return ts.parameterNamePart; + case 337 /* JSDocPropertyTag */: + return ts.propertyNamePart; + case 334 /* JSDocTemplateTag */: + return ts.typeParameterNamePart; + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + return ts.typeAliasNamePart; + default: + return ts.textPart; } } function getJSDocTagNameCompletions() { @@ -131656,9 +131858,9 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences) { + function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); @@ -131693,26 +131895,35 @@ var ts; ? coalesce(importGroup) : importGroup; }); - // Delete or replace the first import. + // Delete all nodes if there are no imports. if (newImportDecls.length === 0) { - changeTracker.delete(sourceFile, oldImportDecls[0]); + // Consider the first node to have trailingTrivia as we want to exclude the + // "header" comment. + changeTracker.deleteNodes(sourceFile, oldImportDecls, { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, /*hasTrailingComment*/ true); } else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + var replaceOptions = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - // Delete any subsequent imports. - for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + }; + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions); + var hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions); + changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, hasTrailingComment); } } } OrganizeImports.organizeImports = organizeImports; - function removeUnusedImports(oldImports, sourceFile, program) { + function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { + // As a precaution, consider unused import detection to be destructive (GH #43051) + if (skipDestructiveCodeActions) { + return oldImports; + } var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); var jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile); @@ -133190,7 +133401,7 @@ var ts; function getRenameInfo(program, sourceFile, position, options) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); if (renameInfo) { return renameInfo; } @@ -133198,7 +133409,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -133218,7 +133429,7 @@ var ts; if (!declarations || declarations.length === 0) return; // Disallow rename for elements that are defined in the standard TypeScript library. - if (declarations.some(isDefinedInLibraryFile)) { + if (declarations.some(function (declaration) { return isDefinedInLibraryFile(program, declaration); })) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; @@ -133236,6 +133447,10 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), node, sourceFile); } + function isDefinedInLibraryFile(program, declaration) { + var sourceFile = declaration.getSourceFile(); + return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); @@ -134386,7 +134601,7 @@ var ts; diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } } - if (ts.isFunctionLikeDeclaration(node)) { + if (canBeConvertedToAsync(node)) { addConvertToAsyncFunctionDiagnostics(node, checker, diags); } node.forEachChild(check); @@ -134443,11 +134658,11 @@ var ts; returnsPromise(node, checker); } function returnsPromise(node, checker) { - var functionType = checker.getTypeAtLocation(node); - var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); - var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + var signature = checker.getSignatureFromDeclaration(node); + var returnType = signature ? checker.getReturnTypeOfSignature(signature) : undefined; return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } + ts.returnsPromise = returnsPromise; function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } @@ -134529,6 +134744,18 @@ var ts; } return false; } + function canBeConvertedToAsync(node) { + switch (node.kind) { + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + return true; + default: + return false; + } + } + ts.canBeConvertedToAsync = canBeConvertedToAsync; })(ts || (ts = {})); /* @internal */ var ts; @@ -134700,7 +134927,7 @@ var ts; symbolKind = "property" /* memberVariableElement */; } var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (location.parent && location.parent.kind === 202 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing @@ -138324,7 +138551,9 @@ var ts; function getAdjustedRange(sourceFile, startNode, endNode, options) { return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - function getAdjustedStartPosition(sourceFile, node, options) { + function getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment) { + var _a, _b; + if (hasTrailingComment === void 0) { hasTrailingComment = false; } var leadingTriviaOption = options.leadingTriviaOption; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); @@ -138355,6 +138584,15 @@ var ts; // when b is deleted - we delete it return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start; } + // if node has a trailing comments, use comment end position as the text has already been included. + if (hasTrailingComment) { + // Check first for leading comments as if the node is the first import, we want to exclude the trivia; + // otherwise we get the trailing comments. + var comment = ((_a = ts.getLeadingCommentRanges(sourceFile.text, fullStart)) === null || _a === void 0 ? void 0 : _a[0]) || ((_b = ts.getTrailingCommentRanges(sourceFile.text, fullStart)) === null || _b === void 0 ? void 0 : _b[0]); + if (comment) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } // get start position of the line following the line that contains fullstart position // (but only if the fullstart isn't the very beginning of the file) var nextLineStart = fullStart > 0 ? 1 : 0; @@ -138363,6 +138601,35 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } + /** Return the end position of a multiline comment of it is on another line; otherwise returns `undefined`; */ + function getEndPositionOfMultilineTrailingComment(sourceFile, node, options) { + var end = node.end; + var trailingTriviaOption = options.trailingTriviaOption; + if (trailingTriviaOption === TrailingTriviaOption.Include) { + // If the trailing comment is a multiline comment that extends to the next lines, + // return the end of the comment and track it for the next nodes to adjust. + var comments = ts.getTrailingCommentRanges(sourceFile.text, end); + if (comments) { + var nodeEndLine = ts.getLineOfLocalPosition(sourceFile, node.end); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + // Single line can break the loop as trivia will only be this line. + // Comments on subsequest lines are also ignored. + if (comment.kind === 2 /* SingleLineCommentTrivia */ || ts.getLineOfLocalPosition(sourceFile, comment.pos) > nodeEndLine) { + break; + } + // Get the end line of the comment and compare against the end line of the node. + // If the comment end line position and the multiline comment extends to multiple lines, + // then is safe to return the end position. + var commentEndLine = ts.getLineOfLocalPosition(sourceFile, comment.end); + if (commentEndLine > nodeEndLine) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } + } + } + return undefined; + } function getAdjustedEndPosition(sourceFile, node, options) { var _a; var end = node.end; @@ -138378,6 +138645,10 @@ var ts; } return end; } + var multilineEndPosition = getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + if (multilineEndPosition) { + return multilineEndPosition; + } var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd @@ -138389,13 +138660,6 @@ var ts; function isSeparator(node, candidate) { return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 201 /* ObjectLiteralExpression */)); } - function spaces(count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += " "; - } - return s; - } function isThisTypeAnnotatable(containingFunction) { return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction); } @@ -138440,6 +138704,17 @@ var ts; if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); }; + ChangeTracker.prototype.deleteNodes = function (sourceFile, nodes, options, hasTrailingComment) { + if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } + // When deleting multiple nodes we need to track if the end position is including multiline trailing comments. + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment); + var end = getAdjustedEndPosition(sourceFile, node, options); + this.deleteRange(sourceFile, { pos: pos, end: end }); + hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + } + }; ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; @@ -138482,6 +138757,10 @@ var ts; if (options === void 0) { options = useNonAdjustedPositions; } this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; + ChangeTracker.prototype.nodeHasTrailingComment = function (sourceFile, oldNode, configurableEnd) { + if (configurableEnd === void 0) { configurableEnd = useNonAdjustedPositions; } + return !!getEndPositionOfMultilineTrailingComment(sourceFile, oldNode, configurableEnd); + }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { var next = ts.findNextToken(node, node.parent, sourceFile); return next && next.kind === 27 /* CommaToken */ ? next : undefined; @@ -138825,47 +139104,22 @@ var ts; // a, b, c // create change for adding 'e' after 'a' as // - find start of next element after a (it is b) - // - use this start as start and end position in final change - // - build text of change by formatting the text of node + separator + whitespace trivia of b + // - use next element start as start and end position in final change + // - build text of change by formatting the text of node + whitespace trivia of b // in multiline case it will work as // a, // b, // c, // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') - // a,* - // ***insertedtext# + // a, + // insertedtext# // ###b, // c, - // find line and character of the next element - var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); - // find line and character of the token that precedes next element (usually it is separator) - var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); - var prefix = void 0; - var startPos = void 0; - if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { - // next element is located on the same line with separator: - // a,$$$$b - // ^ ^ - // | |-next element - // |-separator - // where $$$ is some leading trivia - // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces - // a, x,$$$$b - // ^ ^ ^ - // | | |-next element - // | |-new inserted node padded with spaces - // |-separator - startPos = nextToken.end; - prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); - } - else { - // next element is located on different line that separator - // let insert position be the beginning of the line that contains next element - startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); - } + var nextNode = containingList[index + 1]; + var startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart()); // write separator and leading trivia of the next element as suffix - var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, startPos); + this.insertNodesAt(sourceFile, startPos, [newNode], { suffix: suffix }); } } else { @@ -139396,7 +139650,9 @@ var ts; case 261 /* ImportEqualsDeclaration */: var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); // For first import, leave header comment in place, otherwise only delete JSDoc comments - deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + deleteNode(changes, sourceFile, node, { + leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine, + }); break; case 199 /* BindingElement */: var pattern = node.parent; @@ -139822,7 +140078,7 @@ var ts; ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code, - ts.Diagnostics.This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, ts.Diagnostics.Type_0_is_not_an_array_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators.code, @@ -140713,7 +140969,7 @@ var ts; functionToConvert = tokenAtPosition.parent.initializer; } else { - functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.canBeConvertedToAsync); } if (!functionToConvert) { return; @@ -140722,6 +140978,9 @@ var ts; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); + if (!ts.returnsPromise(functionToConvertRenamed, checker)) { + return; + } var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray; var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { @@ -142339,6 +142598,10 @@ var ts; if (!importClause || !ts.isStringLiteralLike(declaration.moduleSpecifier)) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; + // A type-only import may not have both a default and named imports, so the only way a name can + // be added to an existing type-only import is adding a named import to existing named bindings. + if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) + return undefined; return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 265 /* NamedImports */) ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.text, canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; @@ -142872,7 +143135,8 @@ var ts; ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, - ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code ]; var errorCodeFixIdMap = (_a = {}, _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code] = [ @@ -142881,6 +143145,9 @@ var ts; _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code] = [ ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers ], + _a[ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, + ], _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code] = [ ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers ], @@ -142919,6 +143186,7 @@ var ts; switch (errorCode) { case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: @@ -142928,16 +143196,23 @@ var ts; } } function doAddOverrideModifierChange(changeTracker, sourceFile, pos) { - var classElement = findContainerClassElement(sourceFile, pos); - changeTracker.insertModifierBefore(sourceFile, 156 /* OverrideKeyword */, classElement); + var classElement = findContainerClassElementLike(sourceFile, pos); + var modifiers = classElement.modifiers || ts.emptyArray; + var staticModifier = ts.find(modifiers, ts.isStaticModifier); + var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var modifierPos = staticModifier ? staticModifier.end : + accessibilityModifier ? accessibilityModifier.end : + classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + var options = accessibilityModifier || staticModifier ? { prefix: " " } : { suffix: " " }; + changeTracker.insertModifierAt(sourceFile, modifierPos, 156 /* OverrideKeyword */, options); } function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { - var classElement = findContainerClassElement(sourceFile, pos); + var classElement = findContainerClassElementLike(sourceFile, pos); var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 156 /* OverrideKeyword */; }); ts.Debug.assertIsDefined(overrideModifier); changeTracker.deleteModifier(sourceFile, overrideModifier); } - function isClassElementHasJSDoc(node) { + function isClassElementLikeHasJSDoc(node) { switch (node.kind) { case 167 /* Constructor */: case 164 /* PropertyDeclaration */: @@ -142945,18 +143220,20 @@ var ts; case 168 /* GetAccessor */: case 169 /* SetAccessor */: return true; + case 161 /* Parameter */: + return ts.isParameterPropertyDeclaration(node, node.parent); default: return false; } } - function findContainerClassElement(sourceFile, pos) { + function findContainerClassElementLike(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); var classElement = ts.findAncestor(token, function (node) { if (ts.isClassLike(node)) return "quit"; - return isClassElementHasJSDoc(node); + return isClassElementLikeHasJSDoc(node); }); - ts.Debug.assert(classElement && isClassElementHasJSDoc(classElement)); + ts.Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); return classElement; } })(codefix = ts.codefix || (ts.codefix = {})); @@ -143673,11 +143950,11 @@ var ts; var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, 1 /* NoTruncation */); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */) : undefined; } return typeNode || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } @@ -144807,7 +145084,7 @@ var ts; (function (codefix) { var fixId = "fixMissingCallParentheses"; var errorCodes = [ - ts.Diagnostics.This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -147538,7 +147815,7 @@ var ts; 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 flags = ts.getSyntacticModifierFlags(exportNode); + var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ExportDefault */ : 0 /* None */); var wasDefault = !!(flags & 512 /* Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { @@ -147566,6 +147843,11 @@ var ts; ts.Debug.assert(!wasDefault, "Can't have a default flag here"); return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } + case 267 /* ExportAssignment */: { + var node = exportNode; + var exp = node.expression; + return node.isExportEquals ? undefined : { exportNode: node, exportName: exp, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol }; + } default: return undefined; } @@ -147577,7 +147859,14 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + 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]))); + } + else { + changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + } } else { var exportKeyword = ts.Debug.checkDefined(ts.findModifier(exportNode, 92 /* ExportKeyword */), "Should find an export keyword in modifier list"); @@ -147604,7 +147893,7 @@ var ts; changes.insertNodeAfter(exportingSourceFile, exportNode, ts.factory.createExportDefault(ts.factory.createIdentifier(exportName.text))); break; default: - ts.Debug.assertNever(exportNode, "Unexpected exportNode kind " + exportNode.kind); + ts.Debug.fail("Unexpected exportNode kind " + exportNode.kind); } } } @@ -148533,7 +148822,7 @@ var ts; return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } var cursorRequest = length === 0 && invoked; - var startToken = ts.getTokenAtPosition(sourceFile, span.start); + var startToken = ts.findFirstNonJsxWhitespaceToken(sourceFile, span.start); var endToken = ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)); /* If the refactoring command is invoked through a keyboard action it's safe to assume that the user is actively looking for refactoring actions at the span location. As they may not know the exact range that will trigger a refactoring, we expand the @@ -152342,8 +152631,8 @@ var ts; var list = createNode(338 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; addSyntheticNodes(list._children, pos, node.pos, parent); list._children.push(node); pos = node.end; @@ -152785,7 +153074,7 @@ var ts; break; case 161 /* Parameter */: // Only consider parameter properties - if (!ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { break; } // falls through @@ -153366,7 +153655,7 @@ var ts; // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); } function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); @@ -153411,8 +153700,13 @@ 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" - ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind."); - return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + 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); + } } // We didn't already have the file. Fall through and acquire it from the registry. } @@ -153441,7 +153735,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); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); }); program = undefined; // TODO: GH#18217 } @@ -153541,7 +153835,7 @@ var ts; function shouldGetType(sourceFile, node, position) { switch (node.kind) { case 78 /* Identifier */: - return !ts.isLabelName(node) && !ts.isTagName(node); + return !ts.isLabelName(node) && !ts.isTagName(node) && !ts.isConstTypeReference(node.parent); case 202 /* PropertyAccessExpression */: case 158 /* QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` @@ -153707,15 +154001,7 @@ var ts; function getNavigationTree(fileName) { return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); } - function isTsOrTsxFile(fileName) { - var kind = ts.getScriptKind(fileName, host); - return kind === 3 /* TS */ || kind === 4 /* TSX */; - } function getSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return []; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "2020" /* TwentyTwenty */) { @@ -153726,10 +154012,6 @@ var ts; } } function getEncodedSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return { spans: [], endOfLineState: 0 /* None */ }; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "original" /* Original */) { @@ -153820,13 +154102,13 @@ var ts; var formatContext = ts.formatting.getFormatContext(formatOptions, host); return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions, preferences) { + function organizeImports(args, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - ts.Debug.assert(scope.type === "file"); - var sourceFile = getValidSourceFile(scope.fileName); + ts.Debug.assert(args.type === "file"); + var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 1210fe11bb963..cb161b6a6e3ba 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -85,7 +85,7 @@ var ts; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-beta"; + ts.version = "4.3.1-rc"; /* @internal */ var Comparison; (function (Comparison) { @@ -2651,11 +2651,11 @@ var ts; this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : - this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" : + this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; - var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0; + var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); } }, @@ -3676,7 +3676,7 @@ var ts; }; } var reverseMappedProperties = {}; - if (objectFlags & 2048 /* ReverseMapped */) { + if (objectFlags & 1024 /* ReverseMapped */) { var reverseMappedType = type; reverseMappedProperties = { reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id, @@ -4217,7 +4217,7 @@ var ts; 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. - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 18654] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; @@ -4418,7 +4418,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; - NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -4771,6 +4770,9 @@ var ts; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags + // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check + // for a certain TypeFlags value to determine their meaning. var ObjectFlags; (function (ObjectFlags) { ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; @@ -4783,50 +4785,59 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; - ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; - ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; - ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; - ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; - ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; - ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 1024] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 2048] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 4096] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 8192] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 16384] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ArrayLiteral"] = 32768] = "ArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 262144] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; + ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 1048576] = "CouldContainTypeVariablesComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; + ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 2097152] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags"; + // Object flags that uniquely identify the kind of ObjectType /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; + ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask"; + // Flags that require TypeFlags.Object + ObjectFlags[ObjectFlags["ContainsSpread"] = 4194304] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 8388608] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone"; + // Flags that require TypeFlags.Object and ObjectFlags.Reference /* @internal */ - ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated"; /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists"; + // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; + ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; + ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; - // Object flags that uniquely identify the kind of ObjectType + ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + // Flags that require TypeFlags.Union + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 67108864] = "ContainsIntersections"; + // Flags that require TypeFlags.Intersection /* @internal */ - ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask"; + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 67108864] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 134217728] = "IsNeverIntersection"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -4900,16 +4911,17 @@ var ts; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple"; - InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType"; - InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType"; - InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint"; - InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional"; - InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType"; - InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof"; - InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict"; - InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue"; - InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination"; + InferencePriority[InferencePriority["SubstituteSource"] = 4] = "SubstituteSource"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 8] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 16] = "PartialHomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 32] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ContravariantConditional"] = 64] = "ContravariantConditional"; + InferencePriority[InferencePriority["ReturnType"] = 128] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 256] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 512] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 1024] = "AlwaysStrict"; + InferencePriority[InferencePriority["MaxValue"] = 2048] = "MaxValue"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 416] = "PriorityImpliesCombination"; InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); /* @internal */ @@ -7846,7 +7858,7 @@ var ts; A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), - An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), @@ -7872,6 +7884,7 @@ var ts; A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), @@ -7958,7 +7971,7 @@ var ts; Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."), - The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."), + The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8000,6 +8013,7 @@ var ts; The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), + Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."), 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), @@ -8248,14 +8262,13 @@ var ts; The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), - Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), @@ -8278,17 +8291,17 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), @@ -8373,7 +8386,7 @@ var ts; Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), @@ -8381,14 +8394,14 @@ var ts; _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), - A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), @@ -8450,7 +8463,7 @@ var ts; The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), - This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_2774", "This condition will always return true since this function appears to always be defined. Did you mean to call it instead?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), @@ -8477,7 +8490,7 @@ var ts; The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), - This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined_2801", "This condition will always return true since this '{0}' appears to always be defined."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), @@ -8486,6 +8499,9 @@ var ts; This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), + Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), + Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), 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}'."), @@ -8583,7 +8599,7 @@ var ts; This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), - This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_becaus_4115", "This parameter property must be rewritten as a property declaration with an 'override' modifier because it overrides a member in base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), 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."), @@ -8619,7 +8635,7 @@ var ts; Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), - Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), @@ -8632,12 +8648,14 @@ var ts; Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), - A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -8861,7 +8879,11 @@ var ts; Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), - Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -8909,6 +8931,7 @@ var ts; _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), 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."), @@ -8950,7 +8973,7 @@ var ts; Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -8990,7 +9013,7 @@ var ts; JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), @@ -9675,11 +9698,11 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; /* @internal */ - function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { - if (stopAtComments === void 0) { stopAtComments = false; } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (ts.positionIsSynthesized(pos)) { return pos; } + var canConsumeStar = false; // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -9694,6 +9717,7 @@ var ts; if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case 9 /* tab */: case 11 /* verticalTab */: @@ -9713,6 +9737,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { @@ -9724,6 +9749,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } break; @@ -9733,12 +9759,21 @@ var ts; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; case 35 /* hash */: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42 /* asterisk */: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -11789,7 +11824,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; + return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -12105,7 +12140,7 @@ var ts; if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } ts.getNameOfDeclaration = getNameOfDeclaration; /*@internal*/ @@ -12660,7 +12695,7 @@ var ts; ts.isModifierKind = isModifierKind; /* @internal */ function isParameterPropertyModifier(kind) { - return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + return !!(ts.modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */); } ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ @@ -13620,7 +13655,9 @@ var ts; } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { @@ -13873,7 +13910,9 @@ var ts; if (node.kind === 338 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ false, isInJSDoc(node)); } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -15308,6 +15347,10 @@ var ts; return node.kind === 177 /* TypeQuery */; } ts.isPartOfTypeQuery = isPartOfTypeQuery; + function isNamespaceReexportDeclaration(node) { + return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 273 /* ExternalModuleReference */; } @@ -15920,6 +15963,7 @@ var ts; parent.kind === 267 /* ExportAssignment */ || parent.kind === 164 /* PropertyDeclaration */ || parent.kind === 234 /* ExpressionStatement */ && node.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 243 /* ReturnStatement */ || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) { return parent; @@ -19120,6 +19164,10 @@ var ts; return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; + function getUseDefineForClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === 99 /* ESNext */ : compilerOptions.useDefineForClassFields; + } + ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return oldOptions !== newOptions && ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); @@ -19191,19 +19239,33 @@ var ts; } (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); } - } + }, + setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { + this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); + var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var cache = createSymlinkCache(cwd, getCanonicalFileName); - var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { - return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + var symlinks = ts.flatMap(files, function (sf) { + var pairs = sf.resolvedModules && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedModules.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) ? [res.resolvedFileName, res.originalPath] : undefined; + })); + return ts.concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] : undefined; }))); - })); + }); for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); @@ -20200,7 +20262,11 @@ var ts; var ts; (function (ts) { function createParenthesizerRules(factory) { + var binaryLeftOperandParenthesizerCache; + var binaryRightOperandParenthesizerCache; return { + getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName, @@ -20221,6 +20287,24 @@ var ts; parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType, parenthesizeTypeArguments: parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); }; + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); }; + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } /** * Determines whether the operand to a BinaryExpression needs to be parenthesized. * @@ -20549,6 +20633,8 @@ var ts; } ts.createParenthesizerRules = createParenthesizerRules; ts.nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; }, + getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; }, parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; }, parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; }, parenthesizeExpressionOfComputedPropertyName: ts.identity, @@ -21490,6 +21576,7 @@ var ts; case 155 /* BigIntKeyword */: case 141 /* NeverKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 147 /* StringKeyword */: case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: @@ -21572,15 +21659,15 @@ var ts; if (flags & 32 /* Static */) { result.push(createModifier(123 /* StaticKeyword */)); } + if (flags & 16384 /* Override */) { + result.push(createModifier(156 /* OverrideKeyword */)); + } if (flags & 64 /* Readonly */) { result.push(createModifier(142 /* ReadonlyKeyword */)); } if (flags & 256 /* Async */) { result.push(createModifier(129 /* AsyncKeyword */)); } - if (flags & 16384 /* Override */) { - result.push(createModifier(156 /* OverrideKeyword */)); - } return result; } // @@ -21652,7 +21739,7 @@ var ts; propagateChildFlags(node.questionToken); if (questionToken) node.transformFlags |= 1 /* ContainsTypeScript */; - if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */) + if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */) node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) node.transformFlags |= 512 /* ContainsES2015 */; @@ -22319,7 +22406,7 @@ var ts; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { var node = createBaseBindingLikeDeclaration(199 /* BindingElement */, /*decorators*/ undefined, - /*modifiers*/ undefined, name, initializer); + /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= @@ -29155,6 +29242,7 @@ var ts; case 324 /* JSDocPrivateTag */: case 325 /* JSDocProtectedTag */: case 326 /* JSDocReadonlyTag */: + case 321 /* JSDocDeprecatedTag */: return visitNode(cbNode, node.tagName) || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); case 340 /* PartiallyEmittedExpression */: @@ -31245,19 +31333,21 @@ var ts; function parseParameterWorker(inOuterAwaitContext) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); + // 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(); if (token() === 107 /* ThisKeyword */) { - var node_1 = factory.createParameterDeclaration( - /*decorators*/ undefined, + var node_1 = factory.createParameterDeclaration(decorators, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); + if (decorators) { + parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } return withJSDoc(finishNode(node_1, pos), hasJSDoc); } - // 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 savedTopLevel = topLevel; topLevel = false; var modifiers = parseModifiers(); @@ -33543,12 +33633,13 @@ var ts; // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var openBracePosition = scanner.getTokenPos(); if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { var multiLine = scanner.hasPrecedingLineBreak(); var statements = parseList(1 /* BlockStatements */, parseStatement); parseExpectedMatchingBrackets(18 /* OpenBraceToken */, 19 /* CloseBraceToken */, openBracePosition); - var result = finishNode(factory.createBlock(statements, multiLine), pos); + var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); if (token() === 62 /* EqualsToken */) { parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); nextToken(); @@ -33557,7 +33648,7 @@ var ts; } else { var statements = createMissingList(); - return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -33584,11 +33675,13 @@ var ts; } function parseEmptyStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(26 /* SemicolonToken */); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(98 /* IfKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); @@ -33596,10 +33689,11 @@ var ts; parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var thenStatement = parseStatement(); var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(89 /* DoKeyword */); var statement = parseStatement(); parseExpected(114 /* WhileKeyword */); @@ -33612,20 +33706,22 @@ var ts; // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. parseOptional(26 /* SemicolonToken */); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(114 /* WhileKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(96 /* ForKeyword */); var awaitToken = parseOptionalToken(130 /* AwaitKeyword */); parseExpected(20 /* OpenParenToken */); @@ -33661,34 +33757,37 @@ var ts; parseExpected(21 /* CloseParenToken */); node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(kind === 242 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); var node = kind === 242 /* BreakStatement */ ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(104 /* ReturnKeyword */); var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(115 /* WithKeyword */); var openParenPosition = scanner.getTokenPos(); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpectedMatchingBrackets(20 /* OpenParenToken */, 21 /* CloseParenToken */, openParenPosition); var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { var pos = getNodePos(); @@ -33717,17 +33816,19 @@ var ts; } function parseSwitchStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(106 /* SwitchKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { // ThrowStatement[Yield] : // throw [no LineTerminator here]Expression[In, ?Yield]; var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(108 /* ThrowKeyword */); // Because of automatic semicolon insertion, we need to report error if this // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' @@ -33740,11 +33841,12 @@ var ts; expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } // TODO: Review for error recovery function parseTryStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(110 /* TryKeyword */); var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -33755,7 +33857,7 @@ var ts; parseExpected(95 /* FinallyKeyword */); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { var pos = getNodePos(); @@ -33774,9 +33876,10 @@ var ts; } function parseDebuggerStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(86 /* DebuggerKeyword */); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement() { // Avoiding having to do the lookahead for a labeled statement by just trying to parse @@ -35163,7 +35266,6 @@ var ts; state = 2 /* SavingComments */; var commentEnd = scanner.getStartPos(); var linkStart = scanner.getTextPos() - 1; - // TODO: redo here var link = parseJSDocLink(linkStart); if (link) { if (!linkEnd) { @@ -35365,8 +35467,9 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */ || !previousWhitespace && state === 2 /* SavingComments */) { - // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace + if (state === 3 /* SavingBackticks */ + || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace comments.push(scanner.getTokenText()); break; } @@ -35443,6 +35546,10 @@ var ts; return comments.join(""); } } + function isNextJSDocTokenWhitespace() { + var next = nextTokenJSDoc(); + return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */; + } function parseJSDocLink(start) { if (!tryParse(parseJSDocLinkPrefix)) { return undefined; @@ -36946,8 +37053,8 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - /* @internal */ - ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsWithoutBuild = [ + // CommandLine only options { name: "all", type: "boolean", @@ -37733,7 +37840,9 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins }, - ]); + ]; + /* @internal */ + ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsWithoutBuild); /* @internal */ ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); /* @internal */ @@ -37748,8 +37857,7 @@ var ts; ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) { return ts.hasProperty(option, "transpileOptionValue"); }); - /* @internal */ - ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsOnlyBuild = [ { name: "verbose", shortName: "v", @@ -37777,7 +37885,9 @@ var ts; description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean" } - ]); + ]; + /* @internal */ + ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsOnlyBuild); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -37831,6 +37941,10 @@ var ts; return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations)); } ts.getOptionsNameMap = getOptionsNameMap; + var compilerOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; /* @internal */ ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, @@ -37892,6 +38006,10 @@ var ts; return option.name; } function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { + var _a; + if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -38046,6 +38164,7 @@ var ts; } /*@internal*/ ts.compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -38078,7 +38197,12 @@ var ts; function getBuildOptionsNameMap() { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts)); } + var buildOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap: getOptionsNameMap + }; var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: ts.buildOpts, unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, @@ -39829,13 +39953,24 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) { var traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined; + var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -39858,6 +39993,8 @@ var ts; trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); } } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -39868,17 +40005,31 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary: primary, + resolvedFileName: resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId: packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, result); + if (traceEnabled) + traceResult(result); + return result; + function traceResult(result) { + var _a; + if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { // Check primary library paths if (typeRoots && typeRoots.length) { @@ -39908,20 +40059,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = void 0; + var result_4; if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); - result = searchResult && searchResult.value; + result_4 = searchResult && searchResult.value; } else { var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; - result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); - } - var resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); } - return resolvedFile; + return resolvedTypeScriptOnly(result_4); } else { if (traceEnabled) { @@ -39976,22 +40123,21 @@ var ts; return result; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName); - } - ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ function createCacheWithRedirects(options) { var ownMap = new ts.Map(); var redirectsMap = new ts.Map(); return { - ownMap: ownMap, + getOwnMap: getOwnMap, redirectsMap: redirectsMap, getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, clear: clear, setOwnOptions: setOwnOptions, setOwnMap: setOwnMap }; + function getOwnMap() { + return ownMap; + } function setOwnOptions(newOptions) { options = newOptions; } @@ -40017,26 +40163,88 @@ var ts; } } ts.createCacheWithRedirects = createCacheWithRedirects; - /*@internal*/ - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap }; + function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + var cache; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear }; + function getPackageJsonInfo(packageJsonPath) { + return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + if (!options.configFile) + return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + // The own map will be for projectCompilerOptions + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + // Set correct own map + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + var ref = { + sourceFile: options.configFile, + commandLine: { options: options } + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options); + } + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) { + return { + getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, + clear: clear, + update: update, + }; + function clear() { + directoryToModuleNameMap.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap); + } function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); }); } + } + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + var preDirectoryResolutionCache = 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; } }); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + packageJsonInfoCache.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); + } function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } - function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { - var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - var result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; - } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); return { get: get, set: set }; @@ -40103,7 +40311,17 @@ var ts; } } } - ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + ts.createModuleResolutionCache = createModuleResolutionCache; + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache.clear(); + } + } + ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache) { var containingDirectory = ts.getDirectoryPath(containingFile); var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -40381,7 +40599,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; 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, state.resultFromCache); function tryResolve(extensions) { @@ -40441,7 +40659,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -40474,8 +40692,9 @@ var ts; * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo" * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo" */ + /* @internal */ function parseNodeModuleFromPath(resolved) { - var path = ts.normalizePath(resolved.path); + var path = ts.normalizePath(resolved); var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; @@ -40487,6 +40706,7 @@ var ts; } return path.slice(0, indexAfterPackageName); } + ts.parseNodeModuleFromPath = parseNodeModuleFromPath; function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; @@ -40570,21 +40790,43 @@ var ts; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c; var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) + trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) + trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + var directoryExists = ts.directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = ts.readJson(packageJsonPath, host); if (traceEnabled) { trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists); // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results state.failedLookupLocations.push(packageJsonPath); } @@ -40833,7 +41075,7 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath @@ -40874,13 +41116,13 @@ var ts; * This is the minumum code needed to expose that functionality; the rest is in the host. */ /* @internal */ - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { 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 state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache); } @@ -41526,6 +41768,7 @@ var ts; } if (node.kind === 298 /* SourceFile */) { node.flags |= emitFlags; + node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -42843,9 +43086,9 @@ var ts; var saveCurrentFlow = currentFlow; for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { var typeAlias = delayedTypeAliases_1[_i]; - var host = ts.getJSDocHost(typeAlias); - container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); })) || file; - blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file; + var host = typeAlias.parent.parent; + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -43431,8 +43674,8 @@ var ts; } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + // Incorrect export assignment in some sort of block construct + bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node)); } else { var flags = ts.exportAssignmentIsAlias(node) @@ -44610,6 +44853,7 @@ var ts; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -44618,7 +44862,7 @@ var ts; var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384 /* FreshLiteral */; var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); @@ -44805,6 +45049,7 @@ var ts; return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, + getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, argumentCount) { return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */); @@ -44976,14 +45221,14 @@ var ts; var autoType = createIntrinsicType(1 /* Any */, "any"); var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); - var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */); + var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 131072 /* ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -45009,7 +45254,7 @@ var ts; var voidType = createIntrinsicType(16384 /* Void */, "void"); var neverType = createIntrinsicType(131072 /* Never */, "never"); var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -45021,7 +45266,7 @@ var ts; var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -45030,7 +45275,7 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */; + anyFunctionType.objectFlags |= 524288 /* NonInferrableType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -45692,7 +45937,7 @@ var ts; } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property - return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -45720,7 +45965,7 @@ var ts; return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); @@ -45855,7 +46100,7 @@ var ts; case 164 /* PropertyDeclaration */: // static properties in classes introduce temporary variables if (ts.hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + return target < 99 /* ESNext */ || !useDefineForClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -46240,7 +46485,7 @@ var ts; } // Perform extra checks only if error reporting was requested if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* 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. @@ -46571,8 +46816,7 @@ var ts; } } function getDeclarationOfAliasSymbol(symbol) { - var _a; - return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(isAliasSymbolDeclaration); + return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration); } /** * An alias symbol is created by one of the following declarations: @@ -46587,6 +46831,7 @@ var ts; * module.exports = * {} * {name: } + * const { x } = require ... */ function isAliasSymbolDeclaration(node) { return node.kind === 261 /* ImportEqualsDeclaration */ @@ -46817,7 +47062,7 @@ var ts; return undefined; } var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -47893,7 +48138,7 @@ var ts; var _loop_8 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } } @@ -47908,7 +48153,7 @@ var ts; // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred // to one another anyway) - if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) { + if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } break; @@ -47940,7 +48185,7 @@ var ts; if (typeof state_2 === "object") return state_2.value; } - return callback(globals); + return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace @@ -47960,11 +48205,11 @@ var ts; /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) */ - function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols, ignoreQualification); + var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables.pop(); return result; } @@ -47982,7 +48227,7 @@ var ts; !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols, ignoreQualification) { + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { // If symbol is directly available by its name in the symbol table if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; @@ -47995,6 +48240,8 @@ var ts; && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // If we're looking up a local name to reference directly, omit namespace reexports, otherwise when we're trawling through an export list to make a dotted name, we can keep it + && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */))) { @@ -48097,7 +48344,7 @@ var ts; return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -48358,7 +48605,7 @@ var ts; return flags & 814775659 /* NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { - return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */)); + return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* Object */) && !!(ts.getObjectFlags(type) & 16777216 /* IsClassInstanceClone */))); } function createNodeBuilder() { return { @@ -48971,7 +49218,7 @@ var ts; } if (resolvedType.stringIndexInfo) { var indexSignature = void 0; - if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + if (resolvedType.objectFlags & 1024 /* ReverseMapped */) { indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context)); } else { @@ -49015,10 +49262,23 @@ var ts; } return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + // Use placeholders for reverse mapped types we've either already descended into, or which + // are nested reverse mappings within a mapping over a non-anonymous type. The later is a restriction mostly just to + // reduce the blowup in printback size from doing, eg, a deep reverse mapping over `Window`. + // Since anonymous types usually come from expressions, this allows us to preserve the output + // for deep mappings which likely come from expressions, while truncating those parts which + // come from mappings over library functions. + return !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) + && (ts.contains(context.reverseMappedStack, propertySymbol) + || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0]) + && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16 /* Anonymous */))); + } function addPropertyToElementList(propertySymbol, context, typeElements) { var _a; var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */); - var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; @@ -49050,16 +49310,20 @@ var ts; } } else { - var savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; var propertyTypeNode = void 0; - if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } } - context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; @@ -49100,25 +49364,25 @@ var ts; var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); /** Map from type reference identifier text to [type, index in `result` where the type node is] */ var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; - var result_4 = []; + var result_5 = []; var i = 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result_4.push(typeNode_1); + result_5.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result_4.push(typeNode); + result_5.push(typeNode); if (seenNames && ts.isIdentifierTypeReference(typeNode)) { - seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]); + seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]); } } } @@ -49140,13 +49404,13 @@ var ts; })) { for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var _a = types_3[_i], type = _a[0], resultIndex = _a[1]; - result_4[resultIndex] = typeToTypeNodeHelper(type, context); + result_5[resultIndex] = typeToTypeNodeHelper(type, context); } } }); context.flags = saveContextFlags; } - return result_4; + return result_5; } } function typesAreSameReference(a, b) { @@ -49480,7 +49744,7 @@ var ts; // specifier preference var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map()); links.specifierCache.set(contextFile.path, specifier); } @@ -49770,13 +50034,13 @@ var ts; function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { if (type !== errorType && enclosingDeclaration) { var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) { // try to reuse the existing annotation var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); - if (result_5) { - return result_5; + var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_6) { + return result_6; } } } @@ -49793,10 +50057,14 @@ var ts; function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { if (type !== errorType && context.enclosingDeclaration) { var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); - if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) { + var annotated = getTypeFromTypeNode(annotation); + var thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -51550,7 +51818,7 @@ var ts; var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= 131072 /* ObjectRestType */; + result.objectFlags |= 8388608 /* ObjectRestType */; return result; } function isGenericTypeWithUndefinedConstraint(type) { @@ -51858,6 +52126,22 @@ var ts; } ; } + /** Create a synthetic property access flow node after the last statement of the file */ + function getFlowTypeFromCommonJSExport(symbol) { + var file = ts.getSourceFileOfNode(symbol.declarations[0]); + var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName); + var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); }); + var reference = areAllModuleExports + ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName) + : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + ts.setParent(reference.expression.expression, reference.expression); + } + ts.setParent(reference.expression, reference); + ts.setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); + } function getFlowTypeInConstructor(symbol, constructor) { var accessName = ts.startsWith(symbol.escapedName, "__#") ? ts.factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) @@ -51973,7 +52257,7 @@ var ts; mergeSymbolTable(exports, s.exports); } var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - type.objectFlags |= 16384 /* JSLiteral */; + type.objectFlags |= 8192 /* JSLiteral */; return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { @@ -52074,9 +52358,9 @@ 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.stringIndexInfo, exportedType.numberIndexInfo); - result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + result.objectFlags |= (ts.getObjectFlags(type) & 8192 /* JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { - result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type + result.objectFlags |= 16777216 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type } return result; } @@ -52135,7 +52419,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -52159,7 +52443,7 @@ var ts; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -52178,7 +52462,7 @@ var ts; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -52435,38 +52719,31 @@ var ts; if (writing === void 0) { writing = false; } var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); // For write operations, prioritize type annotations on the setter - if (writing) { - var setterParameterType_1 = getAnnotatedAccessorType(setter); - if (setterParameterType_1) { - var flags = ts.getCheckFlags(symbol); - if (flags & 1 /* Instantiated */) { - var links = getSymbolLinks(symbol); - return instantiateType(setterParameterType_1, links.mapper); - } - return setterParameterType_1; - } + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); } // Else defer to the getter type if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } // Try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + var getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + if (setterType) { + return setterType; } // If there are no specified types, try to infer it from the body of the get accessor if it exists. if (getter && getter.body) { - return getReturnTypeFromBody(getter); + var returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); } // Otherwise, fall back to 'any'. if (setter) { @@ -52483,6 +52760,13 @@ var ts; return anyType; } return undefined; + function instantiateTypeIfNeeded(type, symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); + } + return type; + } } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); @@ -52547,14 +52831,16 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); + var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontResolveAlias*/ true); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 111551 /* Value */ - ? getTypeOfSymbol(targetSymbol) - : errorType; + links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -54158,6 +54444,12 @@ var ts; } } } + function replaceIndexedAccess(instantiable, type, replacement) { + // map type.indexType to 0 + // map type.objectType to `[TReplacement]` + // thus making the indexed access `[TReplacement][0]` or `TReplacement` + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } function getIndexInfoOfIndexSymbol(indexSymbol, indexKind) { var declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); if (!declaration) @@ -54178,8 +54470,21 @@ var ts; inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ + && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ + && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) { + // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is + // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of + // type identities produced, we simplify such indexed access occurences + var newTypeParam = type.constraintType.type.objectType; + var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.mappedType = newMappedType; + inferredProp.constraintType = getIndexType(newTypeParam); + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -54393,7 +54698,7 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 2048 /* ReverseMapped */) { + else if (type.objectFlags & 1024 /* ReverseMapped */) { resolveReverseMappedTypeMembers(type); } else if (type.objectFlags & 16 /* Anonymous */) { @@ -54812,6 +55117,7 @@ var ts; return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b; var singleProp; var propSet; var indexTypes; @@ -54820,8 +55126,9 @@ var ts; var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var current = _a[_i]; + var mergedInstantiations = false; + for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) { + var current = _c[_i]; var type = getApparentType(current); if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); @@ -54837,13 +55144,25 @@ var ts; singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new ts.Map(); - propSet.set(getSymbolId(singleProp), singleProp); + var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + // If the symbols are instances of one another with identical types - consider the symbols + // equivalent and just use the first one, which thus allows us to avoid eliding private + // members when intersecting a (this-)instantiations of a class with it's raw base or another instance + if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 /* True */ : 0 /* False */; }) === -1 /* True */) { + // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used + // to do when we recorded multiple distinct symbols so that we still get, eg, `Array.length` printed + // back and not `Array.length` when we're looking at a `.length` access on a `string[] | number[]` + mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - var id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new ts.Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + var id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | @@ -54861,7 +55180,7 @@ var ts; checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0); indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304 /* ContainsSpread */)) { checkFlags |= 32 /* WritePartial */; indexTypes = ts.append(indexTypes, undefinedType); } @@ -54877,7 +55196,19 @@ var ts; return undefined; } if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + // No symbol from a union/intersection should have a `.parent` set (since unions/intersections don't act as symbol parents) + // Unless that parent is "reconstituted" from the "first value declaration" on the symbol (which is likely different than its instantiated parent!) + // They also have a `.containingType` set, which affects some services endpoints behavior, like `getRootSymbol` + var clone_1 = createSymbolWithType(singleProp, singleProp.type); + clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent; + clone_1.containingType = containingType; + clone_1.mapper = singleProp.mapper; + return clone_1; + } + else { + return singleProp; + } } var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; @@ -54886,8 +55217,8 @@ var ts; var propTypes = []; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; - for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { - var prop = props_1[_b]; + for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { + var prop = props_1[_d]; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } @@ -54964,15 +55295,15 @@ var ts; * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. */ function getReducedType(type) { - if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 67108864 /* ContainsIntersections */) { return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); } else if (type.flags & 2097152 /* Intersection */) { - if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { - type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); + if (!(type.objectFlags & 67108864 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 67108864 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 134217728 /* IsNeverIntersection */ : 0); } - return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + return type.objectFlags & 134217728 /* IsNeverIntersection */ ? neverType : type; } return type; } @@ -55002,7 +55333,7 @@ var ts; return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); } function elaborateNeverIntersection(errorInfo, type) { - if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + if (type.flags & 2097152 /* Intersection */ && ts.getObjectFlags(type) & 134217728 /* IsNeverIntersection */) { var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); @@ -55159,6 +55490,9 @@ var ts; } return false; } + function isOptionalPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && node.questionToken; + } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; @@ -55313,8 +55647,7 @@ var ts; if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) return undefined; var typeTag = ts.getJSDocTypeTag(node); - var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); @@ -55679,6 +56012,17 @@ var ts; else if (grandParent.kind === 160 /* TypeParameter */ && grandParent.parent.kind === 191 /* MappedType */) { inferences = ts.append(inferences, keyofConstraintType); } + // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends + // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template + // of the check type's mapped type + else if (grandParent.kind === 191 /* MappedType */ && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 185 /* ConditionalType */ && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 191 /* MappedType */ && + grandParent.parent.checkType.type) { + var checkMappedType_1 = grandParent.parent.checkType; + var nodeType = getTypeFromTypeNode(checkMappedType_1.type); + inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); + } } } } @@ -55752,7 +56096,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 3670016 /* PropagatingFlags */; + return result & 917504 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -55881,11 +56225,21 @@ var ts; ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } + // We refrain from associating a local type alias with an instantiation of a top-level type alias + // because the local alias may end up being referenced in an inferred return type where it is not + // accessible--which in turn may lead to a large structural expansion of the type when generating + // a .d.ts file. See #43622 for an example. var aliasSymbol = getAliasSymbolForTypeNode(node); - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol) { + var _a; + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias); + return !!(declaration && ts.getContainingFunction(declaration)); + } function getTypeReferenceName(node) { switch (node.kind) { case 174 /* TypeReference */: @@ -55981,9 +56335,17 @@ var ts; } function getConditionalFlowTypeOfType(type, node) { var constraints; + var covariant = true; while (node && !ts.isStatement(node) && node.kind !== 312 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { + // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but + // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax + if (parent.kind === 161 /* Parameter */) { + covariant = !covariant; + } + // Always substitute on type parameters, regardless of variance, since even + // in contravariant positions, they may rely on substituted constraints to be valid + if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -56575,7 +56937,7 @@ var ts; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; } else { @@ -56777,8 +57139,8 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | - (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 67108864 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } function getUnionOrIntersectionTypePredicate(signatures, kind) { @@ -56836,7 +57198,7 @@ var ts; var typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id; + "#" + origin.type.id + "|" + getTypeListId(types); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { @@ -56963,7 +57325,7 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -56972,7 +57334,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -57001,7 +57363,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -57399,7 +57761,7 @@ var ts; if (noImplicitAny) { return false; // Flag is meaningless under `noImplicitAny` mode } - if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + if (ts.getObjectFlags(type) & 8192 /* JSLiteral */) { return true; } if (type.flags & 1048576 /* Union */) { @@ -57613,6 +57975,13 @@ var ts; } return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) { + type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ | + (isGenericObjectType(type.substitute) || isGenericObjectType(type.baseType) ? 8388608 /* IsGenericObjectType */ : 0); + } + return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); + } return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type) { @@ -57623,6 +57992,13 @@ var ts; } return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) { + type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ | + (isGenericIndexType(type.substitute) || isGenericIndexType(type.baseType) ? 33554432 /* IsGenericIndexType */ : 0); + } + return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); + } return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type); } function isThisTypeParameter(type) { @@ -57880,7 +58256,7 @@ var ts; // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { var isUnwrapped = isTypicalNondistributiveConditional(root); - var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { @@ -57893,7 +58269,7 @@ var ts; // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); } // It's possible for 'infer T' type paramteters to be given uninstantiated constraints when the // those type parameters are used in type references (see getInferredTypeParameterConstraint). For @@ -58150,7 +58526,7 @@ var ts; } } var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return spread; } } @@ -58256,7 +58632,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */ | 4194304 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ @@ -58676,8 +59052,9 @@ var ts; outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || ts.emptyArray; - typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? - ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) : + var allDeclarations_1 = type.objectFlags & 4 /* Reference */ ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) : typeParameters; links.outerTypeParameters = typeParameters; } @@ -58722,7 +59099,7 @@ var ts; return true; } } - return !!ts.forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node) { @@ -58734,6 +59111,9 @@ var ts; getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality case 177 /* TypeQuery */: return true; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + return (!node.type && !!node.body) || !!ts.forEachChild(node, containsReference); } return !!ts.forEachChild(node, containsReference); } @@ -58913,6 +59293,9 @@ var ts; var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; } + if (objectFlags & 1024 /* ReverseMapped */) { + return instantiateReverseMappedType(type, mapper); + } return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; @@ -58962,6 +59345,21 @@ var ts; } return type; } + function instantiateReverseMappedType(type, mapper) { + var innerMappedType = instantiateType(type.mappedType, mapper); + if (!(ts.getObjectFlags(innerMappedType) & 32 /* Mapped */)) { + return type; + } + var innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304 /* Index */)) { + return type; + } + var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); + if (instantiated) { + return instantiated; + } + return type; // Nested invocation of `inferTypeForHomomorphicMappedType` or the `source` instantiated into something unmappable + } function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -59877,7 +60275,7 @@ var ts; return false; } function isIgnoredJsxProperty(source, sourceProp) { - return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); + return ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { while (true) { @@ -59887,6 +60285,7 @@ var ts; type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; @@ -60204,7 +60603,7 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1 /* True */; } - reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */)); return 0 /* False */; } // Normalize the source and target types: Turn fresh literal types into regular literal types, @@ -60247,8 +60646,8 @@ var ts; if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); + var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -60333,7 +60732,7 @@ var ts; // We suppress recursive intersection property checks because they can generate lots of work when relating // recursive intersections that are structurally similar but not exactly identical. See #37854. if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); inPropertyCheck = false; @@ -60342,8 +60741,10 @@ var ts; return result; function reportErrorResults(source, target, result, isComparingJsxAttributes) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; var maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -60390,7 +60791,7 @@ var ts; if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { var sourceUnionOrIntersection = source; var targetUnionOrIntersection = target; - if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144 /* PrimitiveUnion */) { + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536 /* PrimitiveUnion */) { // There's a fast path for comparing primitive unions return; } @@ -60415,11 +60816,11 @@ var ts; } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & 3145728 /* UnionOrIntersection */) { - var result_6 = eachTypeRelatedToSomeType(source, target); - if (result_6) { - result_6 &= eachTypeRelatedToSomeType(target, source); + var result_7 = eachTypeRelatedToSomeType(source, target); + if (result_7) { + result_7 &= eachTypeRelatedToSomeType(target, source); } - return result_6; + return result_7; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -60434,10 +60835,10 @@ var ts; } function hasExcessProperties(source, target, reportErrors) { var _a; - if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; @@ -60851,21 +61252,21 @@ var ts; if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_7 = 0 /* False */; + var result_8 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_8; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_8; } } } @@ -60945,6 +61346,20 @@ var ts; } } else if (target.flags & 8388608 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { + // Relate components directly before falling back to constraint relationships + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } // A type S is related to a type T[K] if S is related to C, where C is the base // constraint of T[K] for writing. if (relation === assignableRelation || relation === comparableRelation) { @@ -60955,11 +61370,24 @@ var ts; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0); var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + // create a new chain for the constraint error + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { // A source type T is related to a target type { [P in X]: T[P] } @@ -61037,23 +61465,14 @@ var ts; // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - var result_8 = inferTypesFromTemplateLiteralType(source, target); - if (result_8 && ts.every(result_8, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + var result_9 = inferTypesFromTemplateLiteralType(source, target); + if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { return -1 /* True */; } } if (source.flags & 8650752 /* TypeVariable */) { - if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { - // A type S[K] is related to a type T[J] if S is related to T and K is related to J. - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - result &= isRelatedTo(source.indexType, target.indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - else { + // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch + if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) { var constraint = getConstraintOfType(source); if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. @@ -61068,7 +61487,7 @@ var ts; 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, reportErrors, /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -61080,6 +61499,16 @@ var ts; return result; } } + else if (source.flags & 134217728 /* TemplateLiteral */) { + if (!(target.flags & 134217728 /* TemplateLiteral */)) { + var baseConstraint = getBaseConstraintOfType(source); + var constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; + } + } + } else if (source.flags & 268435456 /* StringMapping */) { if (target.flags & 268435456 /* StringMapping */ && source.symbol === target.symbol) { if (result = isRelatedTo(source.type, target.type, reportErrors)) { @@ -61106,7 +61535,7 @@ var ts; if (sourceParams) { // If the source has infer type parameters, we instantiate them in the context of the target var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } @@ -61164,7 +61593,7 @@ var ts; return 0 /* False */; } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && - !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + !(ts.getObjectFlags(source) & 4096 /* MarkerType */ || ts.getObjectFlags(target) & 4096 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. @@ -61192,7 +61621,7 @@ var ts; } // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})` // and not `{} <- fresh({}) <- {[idx: string]: any}` - else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) { + else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 /* FreshLiteral */ && !isEmptyObjectType(source)) { return 0 /* False */; } // Even if relationship doesn't hold for unions, intersections, or generic type references, @@ -61230,14 +61659,19 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_9) { - return result_9; + var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_10) { + return result_10; } } } } return 0 /* False */; + function countMessageChainBreadth(info) { + if (!info) + return 0; + return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0); + } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -61299,13 +61733,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_10; + var result_11; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } } @@ -61445,7 +61879,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_11 = unionParent ? 0 /* False */ : -1 /* True */; + var result_12 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -61455,7 +61889,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_11 &= related; + result_12 &= related; } else { if (related) { @@ -61463,17 +61897,17 @@ var ts; } } } - if (unionParent && !result_11 && targetIsOptional) { - result_11 = isRelatedTo(source, undefinedType); + if (unionParent && !result_12 && targetIsOptional) { + result_12 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_11 && reportErrors) { + if (unionParent && !result_12 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_11; + return result_12; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); @@ -62075,7 +62509,7 @@ var ts; // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); - result.objectFlags |= 8192 /* MarkerType */; + result.objectFlags |= 4096 /* MarkerType */; return result; } function getAliasVariances(symbol) { @@ -62249,8 +62683,8 @@ var ts; } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. - function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons @@ -62268,23 +62702,26 @@ var ts; function isDeeplyNestedType(type, stack, depth) { if (depth >= 5) { var identity_1 = getRecursionIdentity(type); - if (identity_1) { - var count = 0; - for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= 5) { - return true; - } + var count = 0; + for (var i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity_1) { + count++; + if (count >= 5) { + return true; } } } } return false; } - // Types with constituents that could circularly reference the type have a recursion identity. The recursion - // identity is some object that is common to instantiations of the type with the same origin. + // The recursion identity of a type is an object identity that is shared among multiple instantiations of the type. + // We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with + // the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all + // instantiations of that type have the same recursion identity. The default recursion identity is the object + // identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly + // reference the type have a recursion identity that differs from the object identity. function getRecursionIdentity(type) { + // Object and array literals are known not to contain recursive references and don't need a recursion identity. if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) { // Deferred type references are tracked through their associated AST node. This gives us finer @@ -62302,6 +62739,9 @@ var ts; return type.target; } } + if (type.flags & 262144 /* TypeParameter */) { + return type.symbol; + } if (type.flags & 8388608 /* IndexedAccess */) { // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A do { @@ -62313,7 +62753,7 @@ var ts; // The root object represents the origin of the conditional type return type.root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; @@ -62451,6 +62891,9 @@ var ts; // 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; }); @@ -62483,12 +62926,30 @@ var ts; function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return isArrayType(type) || hasArrayOrReadonlyArrayBaseType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } - function hasArrayOrReadonlyArrayBaseType(type) { - return !!(ts.getObjectFlags(type) & 4 /* Reference */) - && !!(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */) - && ts.some(getBaseTypes(type.target), isArrayType); + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */)) { + return undefined; + } + if (ts.getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) { + return ts.getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : undefined; + } + type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */; + var target = type.target; + var bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; // If the interface has any members, they may subtype members in the base, so we should do a full structural comparison + } + var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type))); + } + type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */; + return type.cachedEquivalentBaseType = instantiatedBase; } function isEmptyArrayLiteralType(type) { var elementType = getElementTypeOfArrayType(type); @@ -62733,7 +63194,7 @@ var ts; function isObjectTypeWithInferableIndex(type) { return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */); @@ -62766,7 +63227,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -62777,7 +63238,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */; + regularNew.objectFlags |= resolved.objectFlags & ~16384 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -62807,7 +63268,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; - if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304 /* ContainsSpread */)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; names.set(prop.escapedName, prop); @@ -62856,14 +63317,14 @@ var ts; var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (8192 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -62908,7 +63369,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -62934,7 +63395,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -63014,7 +63475,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -63130,16 +63591,16 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) { - return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); + if (objectFlags & 1048576 /* CouldContainTypeVariablesComputed */) { + return !!(objectFlags & 2097152 /* CouldContainTypeVariables */); } var result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 8388608 /* ObjectRestType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { - type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); + type.objectFlags |= 1048576 /* CouldContainTypeVariablesComputed */ | (result ? 2097152 /* CouldContainTypeVariables */ : 0); } return result; } @@ -63199,7 +63660,7 @@ var ts; // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive // arrow function, but is considered partially inferable because property 'a' has an inferable type. function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 524288 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) || isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType); } @@ -63223,14 +63684,18 @@ var ts; } // For all other object types we infer a new object type where the reverse mapping has been // applied to the type of each property. - var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + var reversed = createObjectType(1024 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType, target, constraint) { var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); @@ -63428,7 +63893,7 @@ var ts; if (contravariant === void 0) { contravariant = false; } var bivariant = false; var propagationType; - var inferencePriority = 1024 /* MaxValue */; + var inferencePriority = 2048 /* MaxValue */; var allowComplexConstraintInference = true; var visited; var sourceStack; @@ -63515,8 +63980,8 @@ var ts; // 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 (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || - (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || + (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -63543,7 +64008,7 @@ var ts; clearCachedInferences(inferences); } } - if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -63583,7 +64048,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - inferWithPriority(empty, target.type, 128 /* LiteralKeyof */); + inferWithPriority(empty, target.type, 256 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -63595,6 +64060,13 @@ var ts; inferFromTypes(source.type, target.type); } } + else if (source.flags & 33554432 /* Substitution */) { + inferFromTypes(source.baseType, target); + var oldPriority = priority; + priority |= 4 /* SubstituteSource */; + inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority + priority = oldPriority; + } else if (target.flags & 16777216 /* Conditional */) { invokeOnce(source, target, inferToConditionalType); } @@ -63614,7 +64086,7 @@ var ts; } else { source = getReducedType(source); - if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { + if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` @@ -63652,26 +64124,22 @@ var ts; } (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */); var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; // We stop inferring and report a circularity if we encounter duplicate recursion identities on both // the source side and the target side. var saveExpandingFlags = expandingFlags; - var sourceIdentity = getRecursionIdentity(source) || source; - var targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && ts.contains(sourceStack, sourceIdentity)) + var sourceIdentity = getRecursionIdentity(source); + var targetIdentity = getRecursionIdentity(target); + if (ts.contains(sourceStack, sourceIdentity)) expandingFlags |= 1 /* Source */; - if (targetIdentity && ts.contains(targetStack, targetIdentity)) + if (ts.contains(targetStack, targetIdentity)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { - if (sourceIdentity) - (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) - (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) - targetStack.pop(); - if (sourceIdentity) - sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = -1 /* Circularity */; @@ -63711,7 +64179,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -63763,7 +64231,7 @@ var ts; else { for (var i = 0; i < sources.length; i++) { var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; inferFromTypes(sources[i], t); if (inferencePriority === priority) matched_1[i] = true; @@ -63842,7 +64310,7 @@ var ts; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? 8 /* PartialHomomorphicMappedType */ : 4 /* HomomorphicMappedType */); + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 /* NonInferrableType */ ? 16 /* PartialHomomorphicMappedType */ : 8 /* HomomorphicMappedType */); } } return true; @@ -63850,7 +64318,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */); + inferWithPriority(getIndexType(source), constraintType, 32 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -63879,7 +64347,7 @@ var ts; } else { var savePriority = priority; - priority |= contravariant ? 32 /* ContravariantConditional */ : 0; + priority |= contravariant ? 64 /* ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, target.flags); priority = savePriority; @@ -64002,7 +64470,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -64053,7 +64521,7 @@ var ts; return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); } function isObjectOrArrayLiteralType(type) { - return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */)); + return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 32768 /* ArrayLiteral */)); } function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { @@ -64066,7 +64534,7 @@ var ts; return candidates; } function getContravariantInference(inference) { - return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } function getCovariantInference(inference, signature) { // Extract all object and array literal types and replace them with a single widened and normalized type. @@ -64083,7 +64551,7 @@ var ts; candidates; // If all inferences were made from a position that implies a combined result, infer a union type. // Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ? + var unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -64380,14 +64848,14 @@ var ts; function getKeyPropertyName(unionType) { var types = unionType.types; // We only construct maps for large unions with non-primitive constituents. - if (types.length < 10 || ts.getObjectFlags(unionType) & 262144 /* PrimitiveUnion */) { + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { return undefined; } if (unionType.keyPropertyName === undefined) { // The candidate key property name is the name of the first property with a unit type in one of the // constituent types. var keyPropertyName = ts.forEach(types, function (t) { - return t.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? + return t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) : undefined; }); @@ -64482,7 +64950,8 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, ignoreObjects) { + if (ignoreObjects === void 0) { ignoreObjects = false; } var flags = type.flags; if (flags & 4 /* String */) { return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; @@ -64519,7 +64988,7 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 524288 /* Object */) { + if (flags & 524288 /* Object */ && !ignoreObjects) { return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? @@ -64542,14 +65011,17 @@ var ts; return 0 /* None */; } if (flags & 465829888 /* Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */; } if (flags & 1048576 /* Union */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t); }, 0 /* None */); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* None */); } if (flags & 2097152 /* Intersection */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t); }, 16777215 /* All */); + // 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 /* Primitive */)); + return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */); } return 16777215 /* All */; } @@ -64758,6 +65230,9 @@ var ts; function everyType(type, f) { return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } + function everyContainedType(type, f) { + return type.flags & 3145728 /* UnionOrIntersection */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 1048576 /* Union */) { var types = type.types; @@ -66058,7 +66533,16 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); + return filterType(type, function (t) { + if (!isRelated(t, candidate)) { + return true; + } + var constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } // 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. @@ -66153,17 +66637,20 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 78 /* Identifier */) { + if (location.kind === 78 /* Identifier */ || location.kind === 79 /* PrivateIdentifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true); + } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the @@ -66288,7 +66775,6 @@ var ts; } } function checkIdentifier(node, checkMode) { - var _a; var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -66390,7 +66876,7 @@ var ts; } } else if (isAlias) { - declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -66603,7 +67089,7 @@ var ts; break; case 164 /* PropertyDeclaration */: case 163 /* PropertySignature */: - if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } @@ -67246,16 +67732,16 @@ var ts; // In an assignment expression, the right operand is contextually typed by the type of the left operand. // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return getTypeOfExpression(binaryExpression.left); + case 4 /* ThisProperty */: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case 5 /* Property */: - case 1 /* ExportsProperty */: - case 6 /* Prototype */: - case 3 /* PrototypeProperty */: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. @@ -67276,11 +67762,11 @@ var ts; var id = lhs.expression; var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true); if (parentSymbol) { - var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); - if (annotated) { + var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated_1) { var nameStr = ts.getElementOrPropertyAccessName(lhs); if (nameStr !== undefined) { - return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr); + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr); } } return undefined; @@ -67288,9 +67774,15 @@ var ts; } return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; + // falls through case 2 /* ModuleExports */: - case 4 /* ThisProperty */: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); + var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case 7 /* ObjectDefinePropertyValue */: case 8 /* ObjectDefinePropertyExports */: case 9 /* ObjectDefinePrototypeProperty */: @@ -67311,7 +67803,7 @@ var ts; var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true); return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) { + function getContextualTypeForThisPropertyAssignment(binaryExpression) { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { @@ -67323,8 +67815,6 @@ var ts; } } } - if (kind === 2 /* ModuleExports */) - return undefined; var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression); if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return undefined; @@ -67379,6 +67869,10 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { if (hasBindableName(element)) { @@ -67476,10 +67970,10 @@ var ts; return false; } function discriminateContextualTypeByObjectMembers(node, contextualType) { - return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -67588,7 +68082,7 @@ var ts; case 290 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent, contextFlags); case 291 /* SpreadAssignment */: - return getApparentTypeOfContextualType(parent.parent, contextFlags); + return getContextualType(parent.parent, contextFlags); case 200 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); @@ -67984,7 +68478,7 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 32768 /* ArrayLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; } return literalType; } @@ -68141,7 +68635,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -68269,9 +68763,9 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { - result.objectFlags |= 16384 /* JSLiteral */; + result.objectFlags |= 8192 /* JSLiteral */; } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -68361,14 +68855,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var objectFlags = 4096 /* JsxAttributes */; + var objectFlags = 2048 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -68452,7 +68946,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -68954,7 +69448,7 @@ var ts; // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { @@ -69129,6 +69623,23 @@ var ts; if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); } + if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (compilerOptions.target === 99 /* ESNext */ && !useDefineForClassFields)) { + var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); + var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { + if (n === lexicalClass_1) + return "quit"; + if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); + } + } if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -69218,7 +69729,10 @@ var ts; // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + prop && + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) + && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { @@ -69261,6 +69775,7 @@ var ts; var diagnosticMessage; var declarationName = ts.idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { @@ -69366,7 +69881,10 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + var diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : ts.Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -69377,6 +69895,11 @@ var ts; } diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) && + isEmptyObjectType(containingType); + } function typeHasStaticProperty(propName, containingType) { var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); return prop !== undefined && !!prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); @@ -69843,7 +70366,7 @@ var ts; }); if (!inferenceContext) { applyToReturnTypes(contextualSignature, signature, function (source, target) { - inferTypes(context.inferences, source, target, 64 /* ReturnType */); + inferTypes(context.inferences, source, target, 128 /* ReturnType */); }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); @@ -69893,7 +70416,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* 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 @@ -70338,77 +70861,66 @@ var ts; return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - var belowArgCount = Number.NEGATIVE_INFINITY; - var aboveArgCount = Number.POSITIVE_INFINITY; - var argCount = args.length; + var _a; + var spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } + var min = Number.POSITIVE_INFINITY; // smallest parameter count + var max = Number.NEGATIVE_INFINITY; // largest parameter count + var maxBelow = Number.NEGATIVE_INFINITY; // largest parameter count that is smaller than the number of arguments + var minAbove = Number.POSITIVE_INFINITY; // smallest parameter count that is larger than the number of arguments var closestSignature; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var sig = signatures_8[_i]; - var minCount = getMinArgumentCount(sig); - var maxCount = getParameterCount(sig); - if (minCount < argCount && minCount > belowArgCount) - belowArgCount = minCount; - if (argCount < maxCount && maxCount < aboveArgCount) - aboveArgCount = maxCount; - if (minCount < min) { - min = minCount; + var minParameter = getMinArgumentCount(sig); + var maxParameter = getParameterCount(sig); + // smallest/largest parameter counts + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + max = Math.max(max, maxParameter); + // shortest parameter count *longer than the call*/longest parameter count *shorter than the call* + if (minParameter < args.length && minParameter > maxBelow) + maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) + minAbove = maxParameter; } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); - var paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var spanArray; - var related; - var error = hasRestParameter || hasSpreadArgument ? - hasRestParameter && hasSpreadArgument ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - ts.Diagnostics.Expected_0_arguments_but_got_1; - if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { - var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; - if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : - ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); - } - } - if (!hasSpreadArgument && argCount < min) { - var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } - if (hasRestParameter || hasSpreadArgument) { - spanArray = ts.factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); + var parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : ts.Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + // between min and max, but with no matching overload + return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + // too short: put the error span on the call expression, not any of the args + var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined); + return ts.addRelatedInfo(diagnostic, parameterError); } + return diagnostic; } else { - spanArray = ts.factory.createNodeArray(args.slice(max)); - } - var pos = ts.first(spanArray).pos; - var end = ts.last(spanArray).end; - if (end === pos) { - end++; + // too long; error goes on the excess parameters + var errorSpan = ts.factory.createNodeArray(args.slice(max)); + var pos = ts.first(errorSpan).pos; + var end = ts.last(errorSpan).end; + if (end === pos) { + end++; + } + ts.setTextRangePosEnd(errorSpan, pos, end); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - ts.setTextRangePosEnd(spanArray, pos, end); - var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -71501,7 +72013,7 @@ var ts; var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false); if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) { var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + jsAssignmentType.objectFlags |= 8192 /* JSLiteral */; return getIntersectionType([returnType, jsAssignmentType]); } } @@ -71933,7 +72445,14 @@ var ts; } } function assignContextualParameterTypes(signature, context) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; // This signature has already has a contextual inference performed and cached on it! + } + } if (context.thisParameter) { var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { @@ -72326,17 +72845,17 @@ var ts; return; } var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */; + var errorNode = ts.getEffectiveReturnTypeNode(func) || func; if (type && type.flags & 131072 /* Never */) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { // minimal check: function has syntactic return type annotation and no explicit return statements in the body // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -72351,7 +72870,7 @@ var ts; return; } } - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { @@ -72371,7 +72890,7 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; + returnOnlyType.objectFlags |= 524288 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } } @@ -74172,7 +74691,7 @@ var ts; checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { if (!(func.kind === 167 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } @@ -74629,9 +75148,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); })); + ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -74683,15 +75202,18 @@ var ts; var symbol = getSymbolOfNode(node); var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); - if (getter && setter) { + if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) { + getNodeLinks(getter).flags |= 1 /* TypeChecked */; var getterFlags = ts.getEffectiveModifierFlags(getter); var setterFlags = ts.getEffectiveModifierFlags(setter); if ((getterFlags & 128 /* Abstract */) !== (setterFlags & 128 /* Abstract */)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } if (((getterFlags & 16 /* Protected */) && !(setterFlags & (16 /* Protected */ | 8 /* Private */))) || ((getterFlags & 8 /* Private */) && !(setterFlags & 8 /* Private */))) { - error(node.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } var getterType = getAnnotatedAccessorType(getter); var setterType = getAnnotatedAccessorType(setter); @@ -75251,20 +75773,23 @@ var ts; case 298 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: + var node_2 = d; + var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values - if (!ts.isEntityNameExpression(d.expression)) { + if (!ts.isEntityNameExpression(expression)) { return 1 /* ExportValue */; } - d = d.expression; + d = expression; // The below options all declare an Alias, which is allowed to merge with other values within the importing module. // falls through case 261 /* ImportEqualsDeclaration */: case 264 /* NamespaceImport */: case 263 /* ImportClause */: - var result_12 = 0 /* None */; + var result_13 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); - return result_12; + ts.forEach(target.declarations, function (d) { result_13 |= getDeclarationSpaces(d); }); + return result_13; case 250 /* VariableDeclaration */: case 199 /* BindingElement */: case 252 /* FunctionDeclaration */: @@ -76585,11 +77110,6 @@ var ts; return; if (getFalsyFlags(type)) return; - if (getAwaitedTypeOfPromise(type)) { - errorAndMaybeSuggestAwait(condExpr, - /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_appears_to_always_be_defined, getTypeNameForErrorDisplay(type)); - return; - } var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr; var testedNode = ts.isIdentifier(location) ? location : ts.isPropertyAccessExpression(location) ? location.name @@ -76601,25 +77121,32 @@ var ts; return; } // While it technically should be invalid for any known-truthy value - // to be tested, we de-scope to functions unrefenced in the block as a - // heuristic to identify the most common bugs. There are too many - // false positives for values sourced from type definitions without - // strictNullChecks otherwise. + // to be tested, we de-scope to functions and Promises unreferenced in + // the block as a heuristic to identify the most common bugs. There + // are too many false positives for values sourced from type + // definitions without strictNullChecks otherwise. var callSignatures = getSignaturesOfType(type, 0 /* Call */); - if (callSignatures.length === 0) { + var isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } var testedSymbol = getSymbolAtLocation(testedNode); if (!testedSymbol) { return; } - var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + var isUsed = ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_appears_to_always_be_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait(location, + /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); + } + else { + error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) { + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { return !!ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); @@ -76656,7 +77183,7 @@ var ts; return ts.forEachChild(childNode, check); }); } - function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) { + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { var isUsed = ts.forEachChild(node.right, function visit(child) { if (ts.isIdentifier(child)) { @@ -77979,7 +78506,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - checkMembersForMissingOverrideModifier(node, type, typeWithThis); + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -78014,12 +78541,16 @@ var ts; checkPropertyInitialization(node); } } - function checkMembersForMissingOverrideModifier(node, type, typeWithThis) { + function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); var baseTypeNode = ts.getEffectiveBaseTypeNode(node); var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); var _loop_24 = function (member) { + if (ts.hasAmbientModifier(member)) { + return "continue"; + } if (ts.isConstructorDeclaration(member)) { ts.forEach(member.parameters, function (param) { if (ts.isParameterPropertyDeclaration(param, member)) { @@ -78035,14 +78566,17 @@ var ts; } function checkClassMember(member, memberIsParameterProperty) { var hasOverride = ts.hasOverrideModifier(member); + var hasStatic = ts.hasStaticModifier(member); if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); if (!declaredProp) { return; } + var thisType = hasStatic ? staticType : typeWithThis; + var baseType = hasStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); var baseClassName = typeToString(baseWithThis); - var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); - var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && !baseProp && hasOverride) { error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } @@ -78053,7 +78587,7 @@ var ts; } if (!baseHasAbstract) { var diag = memberIsParameterProperty ? - ts.Diagnostics.This_parameter_property_must_be_rewritten_as_a_property_declaration_with_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; error(member, diag, baseClassName); } @@ -78207,7 +78741,7 @@ var ts; ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { + else if (useDefineForClassFields) { var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 164 /* PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* Transient */) @@ -79083,7 +79617,10 @@ var ts; } } function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + var illegalContextMessage = node.isExportEquals + ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } @@ -79172,10 +79709,12 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, _b = declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (var _i = 0, _b = declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } } @@ -79184,6 +79723,11 @@ var ts; links.exportsChecked = true; } } + function isDuplicatedCommonJSExport(declarations) { + return declarations + && declarations.length > 1 + && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); }); + } function checkSourceElement(node) { if (node) { var saveCurrentNode = currentNode; @@ -79414,7 +79958,8 @@ var ts; if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_1) { + var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent); + if (host_1 || isCallbackTag) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -79422,7 +79967,9 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var lastParamDeclaration = isCallbackTag + ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) + : ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -79638,11 +80185,11 @@ var ts; } switch (location.kind) { case 298 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) + if (!ts.isExternalModule(location)) break; // falls through case 257 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; case 256 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); @@ -79705,6 +80252,16 @@ var ts; }); } } + function copyLocallyVisibleExportSymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + // Similar condition as in `resolveNameHelper` + if (!ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 270 /* NamespaceExport */)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name) { return name.kind === 78 /* Identifier */ && @@ -79744,14 +80301,14 @@ var ts; } return node.parent.kind === 224 /* ExpressionWithTypeArguments */; } - function isJSDocEntryNameReference(node) { + function getJSDocEntryNameReference(node) { while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 303 /* JSDocNameReference */; + return ts.isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node, callback) { var result; @@ -79913,18 +80470,34 @@ var ts; var meaning = name.parent.kind === 174 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (isJSDocEntryNameReference(name)) { + var jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || ts.isJSDocLink(name.parent)) { var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); - } - else if (ts.isJSDocLink(name.parent)) { - var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ true); + var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ false, ts.getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (ts.isQualifiedName(name) && ts.isIdentifier(name.left)) { + // resolve C.m as a static member first + var links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, 0 /* Normal */); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + // then resolve it as an instance member + var s = resolveEntityName(name.left, meaning, /*ignoreErrors*/ false); + if (s) { + var t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } } if (name.parent.kind === 173 /* TypePredicate */) { return resolveEntityName(name, 1 /* FunctionScopedVariable */); } - // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node, ignoreErrors) { @@ -80124,10 +80697,10 @@ var ts; // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { if (expr.parent.kind === 289 /* PropertyAssignment */) { - var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); - var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType; - var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent); - return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex); + var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); + var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; + var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex); } // Array literal assignment - array destructuring pattern var node = ts.cast(expr.parent, ts.isArrayLiteralExpression); @@ -80481,13 +81054,13 @@ var ts; !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && !!parameter.initializer && - !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + !ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameter(parameter) { return !!strictNullChecks && @@ -81195,17 +81768,18 @@ var ts; } break; case 156 /* OverrideKeyword */: + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override"); } else if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); } - else if (flags & 32 /* Static */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "override"); + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); } - if (node.kind === 161 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "override"); + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); } flags |= 16384 /* Override */; lastOverride = modifier; @@ -81217,7 +81791,7 @@ var ts; if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + else if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); } else if (flags & 32 /* Static */) { @@ -81252,9 +81826,6 @@ var ts; else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "override"); - } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } @@ -81267,6 +81838,9 @@ var ts; else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); + } flags |= 32 /* Static */; lastStatic = modifier; break; @@ -81275,7 +81849,7 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } else if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */ && node.kind !== 172 /* IndexSignature */ && node.kind !== 161 /* Parameter */) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; @@ -81316,7 +81890,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + else if (flags & 16384 /* Override */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); } else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { @@ -81358,6 +81932,9 @@ var ts; if (flags & 256 /* Async */ && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -81389,7 +81966,7 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } - if (compilerOptions.noImplicitOverride && flags & 16384 /* Override */) { + if (flags & 16384 /* Override */) { return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 } else if (flags & 256 /* Async */) { @@ -81403,10 +81980,10 @@ var ts; else if ((node.kind === 262 /* ImportDeclaration */ || node.kind === 261 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 161 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 161 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -82690,20 +83267,6 @@ var ts; return ts.isDeclarationName(name); } } - function isSomeImportDeclaration(decl) { - switch (decl.kind) { - case 263 /* ImportClause */: // For default import - case 261 /* ImportEqualsDeclaration */: - case 264 /* NamespaceImport */: - case 266 /* ImportSpecifier */: - return true; - case 78 /* Identifier */: - // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 266 /* ImportSpecifier */; - default: - return false; - } - } var JsxNames; (function (JsxNames) { JsxNames.JSX = "JSX"; @@ -87573,10 +88136,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_1 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_1, node); - ts.setCommentRange(clone_1, node); - return clone_1; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -87661,6 +88224,7 @@ var ts; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var shouldTransformPrivateElements = languageVersion < 99 /* ESNext */; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; @@ -87682,7 +88246,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === 99 /* ESNext */) { + || useDefineForClassFields && options.target === 99 /* ESNext */) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -87841,7 +88405,7 @@ var ts; // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } @@ -88152,7 +88716,7 @@ var ts; if (ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. return languageVersion < 99 /* ESNext */; @@ -88175,7 +88739,6 @@ var ts; /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); @@ -88287,7 +88850,7 @@ var ts; function transformProperty(property, receiver) { var _a; // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) - var emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + var emitAssignment = !useDefineForClassFields; var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; @@ -88392,10 +88955,10 @@ var ts; 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; + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; } } } @@ -90557,9 +91120,9 @@ var ts; function convertJsxChildrenToChildrenPropObject(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) + var result_14 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_14 && factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("children", result_14) ]); } var result = ts.mapDefined(children, transformJsxChildToExpression); @@ -92291,7 +92854,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName); var e; - if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) { var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; @@ -93114,13 +93677,13 @@ var ts; loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); - loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); + loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { - var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; @@ -96066,10 +96629,10 @@ var ts; var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { // TODO(rbuckton): Does this need to be parented? - var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); - ts.setSourceMapRange(clone_5, node); - ts.setCommentRange(clone_5, node); - return clone_5; + var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -97063,8 +97626,6 @@ var ts; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(204 /* CallExpression */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(206 /* TaggedTemplateExpression */); // Substitutes expression identifiers with imported/exported symbols. context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. @@ -97075,7 +97636,6 @@ var ts; var currentModuleInfo; // The ExternalModuleInfo for the current file. var noSubstitution; // Set of nodes for which substitution rules should be ignored. var needUMDDynamicImportHelper; - var bindingReferenceCache; return ts.chainBundle(context, transformSourceFile); /** * Transforms the module aspects of a SourceFile. @@ -98322,10 +98882,6 @@ var ts; return substituteExpressionIdentifier(node); case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 204 /* CallExpression */: - return substituteCallExpression(node); - case 206 /* TaggedTemplateExpression */: - return substituteTaggedTemplateExpression(node); case 216 /* PostfixUnaryExpression */: case 215 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); @@ -98333,99 +98889,41 @@ var ts; return node; } /** - * For an Identifier, gets the import or export binding that it references. - * @returns One of the following: - * - An `Identifier` if node references an external helpers module (i.e., `tslib`). - * - A `SourceFile` if the node references an export in the file. - * - An `ImportClause` or `ImportSpecifier` if the node references an import binding. - * - Otherwise, `undefined`. + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. */ - function getImportOrExportBindingReferenceWorker(node) { + function substituteExpressionIdentifier(node) { + var _a, _b; if (ts.getEmitFlags(node) & 4096 /* HelperName */) { var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); if (externalHelpersModuleName) { - return externalHelpersModuleName; + return factory.createPropertyAccessExpression(externalHelpersModuleName, node); } + return node; } else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if ((exportContainer === null || exportContainer === void 0 ? void 0 : exportContainer.kind) === 298 /* SourceFile */) { - return exportContainer; + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { + return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), + /*location*/ node); } var importDeclaration = resolver.getReferencedImportDeclaration(node); - if (importDeclaration && (ts.isImportClause(importDeclaration) || ts.isImportSpecifier(importDeclaration))) { - return importDeclaration; - } - } - return undefined; - } - /** - * For an Identifier, gets the import or export binding that it references. - * @param removeEntry When `false`, the result is cached to avoid recomputing the result in a later substitution. - * When `true`, any cached result for the node is removed. - * @returns One of the following: - * - An `Identifier` if node references an external helpers module (i.e., `tslib`). - * - A `SourceFile` if the node references an export in the file. - * - An `ImportClause` or `ImportSpecifier` if the node references an import binding. - * - Otherwise, `undefined`. - */ - function getImportOrExportBindingReference(node, removeEntry) { - var result = bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.get(node); - if (!result && !(bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.has(node))) { - result = getImportOrExportBindingReferenceWorker(node); - if (!removeEntry) { - bindingReferenceCache || (bindingReferenceCache = new ts.Map()); - bindingReferenceCache.set(node, result); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || importDeclaration), factory.cloneNode(name)), + /*location*/ node); + } } } - else if (removeEntry) { - bindingReferenceCache === null || bindingReferenceCache === void 0 ? void 0 : bindingReferenceCache.delete(node); - } - return result; - } - function substituteCallExpression(node) { - if (ts.isIdentifier(node.expression) && getImportOrExportBindingReference(node.expression, /*removeEntry*/ false)) { - return ts.isCallChain(node) ? - factory.updateCallChain(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.expression), node.expression), node.questionDotToken, - /*typeArguments*/ undefined, node.arguments) : - factory.updateCallExpression(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.expression), node.expression), - /*typeArguments*/ undefined, node.arguments); - } - return node; - } - function substituteTaggedTemplateExpression(node) { - if (ts.isIdentifier(node.tag) && getImportOrExportBindingReference(node.tag, /*removeEntry*/ false)) { - return factory.updateTaggedTemplateExpression(node, ts.setTextRange(factory.createComma(factory.createNumericLiteral(0), node.tag), node.tag), - /*typeArguments*/ undefined, node.template); - } return node; } - /** - * Substitution for an Identifier expression that may contain an imported or exported - * symbol. - * - * @param node The node to substitute. - */ - function substituteExpressionIdentifier(node) { - var _a, _b; - var result = getImportOrExportBindingReference(node, /*removeEntry*/ true); - switch (result === null || result === void 0 ? void 0 : result.kind) { - case 78 /* Identifier */: - return factory.createPropertyAccessExpression(result, node); - case 298 /* SourceFile */: - return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), - /*location*/ node); - case 263 /* ImportClause */: - return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(result.parent), factory.createIdentifier("default")), - /*location*/ node); - case 266 /* ImportSpecifier */: - var name = result.propertyName || result.name; - return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = result.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || result), factory.cloneNode(name)), - /*location*/ node); - default: - return node; - } - } /** * Substitution for a BinaryExpression that may contain an imported or exported symbol. * @@ -99687,7 +100185,7 @@ var ts; return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } /** - * Determines whether the target of a destructuring assigment refers to an exported symbol. + * Determines whether the target of a destructuring assignment refers to an exported symbol. * * @param node The destructuring target. */ @@ -100871,7 +101369,7 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, + var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, /*preferences*/ undefined); if (!ts.pathIsRelative(specifier)) { // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration @@ -101617,7 +102115,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param)) + if (!ts.hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 78 /* Identifier */) { @@ -102402,32 +102900,32 @@ var ts; } ts.transformNodes = transformNodes; ts.nullTransformationContext = { - get factory() { return ts.factory; }, - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: ts.returnUndefined, + factory: ts.factory, getCompilerOptions: function () { return ({}); }, - getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + getEmitHost: ts.notImplemented, getEmitHelperFactory: ts.notImplemented, + startLexicalEnvironment: ts.noop, + resumeLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + endLexicalEnvironment: ts.returnUndefined, setLexicalEnvironmentFlags: ts.noop, getLexicalEnvironmentFlags: function () { return 0; }, - hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + hoistFunctionDeclaration: ts.noop, addInitializationStatement: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, - requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop, - addDiagnostic: ts.noop, startBlockScope: ts.noop, endBlockScope: ts.returnUndefined, - addBlockScopedVariable: ts.noop + addBlockScopedVariable: ts.noop, + requestEmitHelper: ts.noop, + readEmitHelpers: ts.notImplemented, + enableSubstitution: ts.noop, + enableEmitNotification: ts.noop, + isSubstitutionEnabled: ts.notImplemented, + isEmitNotificationEnabled: ts.notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, + addDiagnostic: ts.noop, }; })(ts || (ts = {})); var ts; @@ -103176,10 +103674,18 @@ var ts; return outputFiles; } ts.emitUsingBuildInfo = emitUsingBuildInfo; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution"; + PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); var moduleKind = ts.getEmitModuleKind(printerOptions); @@ -103218,8 +103724,10 @@ var ts; var detachedCommentsInfo; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; - var _a = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _a.enter, exitComment = _a.exit; - var preprint = createPreprinter(handlers); + var lastSubstitution; + var currentParenthesizerRule; + var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + var parenthesizer = ts.factory.parenthesizer; var emitBinaryExpression = createEmitBinaryExpression(); reset(); return { @@ -103419,7 +103927,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - emit(preprint(hint, node)); + pipelineEmit(hint, node, /*parenthesizerRule*/ undefined); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -103452,13 +103960,40 @@ var ts; function getCurrentLineMap() { return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } - function emit(node) { + function emit(node, parenthesizerRule) { if (node === undefined) return; var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - emitWithContext(node, emitWorker); + pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); } + function emitIdentifierName(node) { + if (node === undefined) + return; + pipelineEmit(2 /* IdentifierName */, node, /*parenthesizerRule*/ undefined); + } + function emitExpression(node, parenthesizerRule) { + if (node === undefined) + return; + pipelineEmit(1 /* Expression */, node, parenthesizerRule); + } + function emitJsxAttributeValue(node) { + pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); + } + function beforeEmitNode(node) { + if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { + preserveSourceNewlines = false; + } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; + var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); + pipelinePhase(emitHint, node); + currentParenthesizerRule = undefined; + } function shouldEmitComments(node) { return !commentsDisabled && !ts.isSourceFile(node); } @@ -103469,484 +104004,504 @@ var ts; !ts.isUnparsedSource(node) && !ts.isUnparsedPrepend(node); } - function beforeEmitWithContext(node, shouldEmitComments, shouldEmitSourceMaps) { - onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); - var emitFlags = ts.getEmitFlags(node); - var commentRange = shouldEmitComments ? ts.getCommentRange(node) : undefined; - var sourceMapRange = shouldEmitSourceMaps ? ts.getSourceMapRange(node) : undefined; - if (preserveSourceNewlines && (emitFlags & 134217728 /* IgnoreSourceNewlines */)) { - preserveSourceNewlines = false; - } - // Emit leading comments - if (commentRange) { - emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = true; - } - } - // Emit leading sourcemap - if (sourceMapRange) { - if (ts.isUnparsedNode(node)) { - ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); - var parsed = getParsedSourceMap(node.parent); - if (parsed && sourceMapGenerator) { - sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); + function getPipelinePhase(phase, emitHint, node) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { + return pipelineEmitWithNotification; } - } - else { - var source = sourceMapRange.source || sourceMapSource; - if (node.kind !== 339 /* NotEmittedStatement */ - && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && sourceMapRange.pos >= 0) { - emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + // falls through + case 1 /* Substitution */: + if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } + return pipelineEmitWithSubstitution; } - if (emitFlags & 64 /* NoNestedSourceMaps */) { - sourceMapsDisabled = true; + // falls through + case 2 /* Comments */: + if (shouldEmitComments(node)) { + return pipelineEmitWithComments; } - } + // falls through + case 3 /* SourceMaps */: + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; + } + // falls through + case 4 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase); } } - function afterEmitWithContext(node, shouldEmitComments, shouldEmitSourceMaps, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines) { - var emitFlags = ts.getEmitFlags(node); - var commentRange = shouldEmitComments ? ts.getCommentRange(node) : undefined; - var sourceMapRange = shouldEmitSourceMaps ? ts.getSourceMapRange(node) : undefined; - // Emit trailing sourcemap - if (sourceMapRange) { - if (!ts.isUnparsedNode(node)) { - if (emitFlags & 64 /* NoNestedSourceMaps */) { - sourceMapsDisabled = false; - } - if (node.kind !== 339 /* NotEmittedStatement */ - && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && sourceMapRange.end >= 0) { - emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); - } - } + function getNextPipelinePhase(currentPhase, emitHint, node) { + return getPipelinePhase(currentPhase + 1, emitHint, node); + } + function pipelineEmitWithNotification(hint, node) { + var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + var savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); } - // Emit trailing comments - if (commentRange) { - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = false; - } - emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + else { + pipelineEmitWithHintWorker(hint, node); } - preserveSourceNewlines = savedPreserveSourceNewlines; onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + // clear the parenthesizer rule as we ascend + currentParenthesizerRule = undefined; } - function emitWithContext(node, emitCallback) { - var savedPreserveSourceNewlines = preserveSourceNewlines; - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; - var emitComments = shouldEmitComments(node); - var emitSourceMaps = shouldEmitSourceMaps(node); - beforeEmitWithContext(node, emitComments, emitSourceMaps); - emitCallback(node); - afterEmitWithContext(node, emitComments, emitSourceMaps, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines); - } - function emitWorker(node) { - switch (node.kind) { - // Literals - case 8 /* NumericLiteral */: - case 9 /* BigIntLiteral */: - return emitNumericOrBigIntLiteral(node); - case 10 /* StringLiteral */: - case 13 /* RegularExpressionLiteral */: - case 14 /* NoSubstitutionTemplateLiteral */: - return emitLiteral(node, /*jsxAttributeEscape*/ false); - case 11 /* JsxText */: - return emitJsxText(node); - // Pseudo-literals - case 15 /* TemplateHead */: - case 16 /* TemplateMiddle */: - case 17 /* TemplateTail */: - return emitLiteral(node, /*jsxAttributeEscape*/ false); - // Identifiers and PrivateIdentifiers - case 78 /* Identifier */: - return emitIdentifier(node); - case 79 /* PrivateIdentifier */: - return emitPrivateIdentifier(node); - // Names - case 158 /* QualifiedName */: - return emitQualifiedName(node); - case 159 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - // Signature elements - case 160 /* TypeParameter */: - return emitTypeParameter(node); - case 161 /* Parameter */: - return emitParameter(node); - case 162 /* Decorator */: - return emitDecorator(node); - // Type members - case 163 /* PropertySignature */: - return emitPropertySignature(node); - case 164 /* PropertyDeclaration */: - return emitPropertyDeclaration(node); - case 165 /* MethodSignature */: - return emitMethodSignature(node); - case 166 /* MethodDeclaration */: - return emitMethodDeclaration(node); - case 167 /* Constructor */: - return emitConstructor(node); - case 168 /* GetAccessor */: - case 169 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 170 /* CallSignature */: - return emitCallSignature(node); - case 171 /* ConstructSignature */: - return emitConstructSignature(node); - case 172 /* IndexSignature */: - return emitIndexSignature(node); - // Types - case 173 /* TypePredicate */: - return emitTypePredicate(node); - case 174 /* TypeReference */: - return emitTypeReference(node); - case 175 /* FunctionType */: - return emitFunctionType(node); - case 176 /* ConstructorType */: - return emitConstructorType(node); - case 177 /* TypeQuery */: - return emitTypeQuery(node); - case 178 /* TypeLiteral */: - return emitTypeLiteral(node); - case 179 /* ArrayType */: - return emitArrayType(node); - case 180 /* TupleType */: - return emitTupleType(node); - case 181 /* OptionalType */: - return emitOptionalType(node); - // SyntaxKind.RestType is handled below - case 183 /* UnionType */: - return emitUnionType(node); - case 184 /* IntersectionType */: - return emitIntersectionType(node); - case 185 /* ConditionalType */: - return emitConditionalType(node); - case 186 /* InferType */: - return emitInferType(node); - case 187 /* ParenthesizedType */: - return emitParenthesizedType(node); - case 188 /* ThisType */: - return emitThisType(); - case 189 /* TypeOperator */: - return emitTypeOperator(node); - case 190 /* IndexedAccessType */: - return emitIndexedAccessType(node); - case 191 /* MappedType */: - return emitMappedType(node); - case 192 /* LiteralType */: - return emitLiteralType(node); - case 193 /* NamedTupleMember */: - return emitNamedTupleMember(node); - case 194 /* TemplateLiteralType */: - return emitTemplateType(node); - case 195 /* TemplateLiteralTypeSpan */: - return emitTemplateTypeSpan(node); - case 196 /* ImportType */: - return emitImportTypeNode(node); - // Binding patterns - case 197 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 198 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 199 /* BindingElement */: - return emitBindingElement(node); - // Expressions - case 200 /* ArrayLiteralExpression */: - return emitArrayLiteralExpression(node); - case 201 /* ObjectLiteralExpression */: - return emitObjectLiteralExpression(node); - case 202 /* PropertyAccessExpression */: - return emitPropertyAccessExpression(node); - case 203 /* ElementAccessExpression */: - return emitElementAccessExpression(node); - case 204 /* CallExpression */: - return emitCallExpression(node); - case 205 /* NewExpression */: - return emitNewExpression(node); - case 206 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 207 /* TypeAssertionExpression */: - return emitTypeAssertionExpression(node); - case 208 /* ParenthesizedExpression */: - return emitParenthesizedExpression(node); - case 209 /* FunctionExpression */: - return emitFunctionExpression(node); - case 210 /* ArrowFunction */: - return emitArrowFunction(node); - case 211 /* DeleteExpression */: - return emitDeleteExpression(node); - case 212 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 213 /* VoidExpression */: - return emitVoidExpression(node); - case 214 /* AwaitExpression */: - return emitAwaitExpression(node); - case 215 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 216 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 217 /* BinaryExpression */: - return emitBinaryExpression(node); - case 218 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 219 /* TemplateExpression */: - return emitTemplateExpression(node); - case 220 /* YieldExpression */: - return emitYieldExpression(node); - case 221 /* SpreadElement */: - return emitSpreadExpression(node); - case 222 /* ClassExpression */: - return emitClassExpression(node); - case 223 /* OmittedExpression */: - return; - case 224 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(node); - case 225 /* AsExpression */: - return emitAsExpression(node); - case 226 /* NonNullExpression */: - return emitNonNullExpression(node); - case 227 /* MetaProperty */: - return emitMetaProperty(node); - case 228 /* SyntheticExpression */: - ts.Debug.fail("SyntheticExpression should never be printed."); - break; - // Misc - case 229 /* TemplateSpan */: - return emitTemplateSpan(node); - case 230 /* SemicolonClassElement */: - return emitSemicolonClassElement(); - // Element - case 231 /* Block */: - return emitBlock(node); - case 232 /* EmptyStatement */: - return emitEmptyStatement(/*isEmbeddedStatement*/ false); - case 233 /* VariableStatement */: - return emitVariableStatement(node); - case 234 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 235 /* IfStatement */: - return emitIfStatement(node); - case 236 /* DoStatement */: - return emitDoStatement(node); - case 237 /* WhileStatement */: - return emitWhileStatement(node); - case 238 /* ForStatement */: - return emitForStatement(node); - case 239 /* ForInStatement */: - return emitForInStatement(node); - case 240 /* ForOfStatement */: - return emitForOfStatement(node); - case 241 /* ContinueStatement */: - return emitContinueStatement(node); - case 242 /* BreakStatement */: - return emitBreakStatement(node); - case 243 /* ReturnStatement */: - return emitReturnStatement(node); - case 244 /* WithStatement */: - return emitWithStatement(node); - case 245 /* SwitchStatement */: - return emitSwitchStatement(node); - case 246 /* LabeledStatement */: - return emitLabeledStatement(node); - case 247 /* ThrowStatement */: - return emitThrowStatement(node); - case 248 /* TryStatement */: - return emitTryStatement(node); - case 249 /* DebuggerStatement */: - return emitDebuggerStatement(node); - // Declarations - case 250 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 251 /* VariableDeclarationList */: - return emitVariableDeclarationList(node); - case 252 /* FunctionDeclaration */: - return emitFunctionDeclaration(node); - case 253 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 254 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 255 /* TypeAliasDeclaration */: - return emitTypeAliasDeclaration(node); - case 256 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 257 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 258 /* ModuleBlock */: - return emitModuleBlock(node); - case 259 /* CaseBlock */: - return emitCaseBlock(node); - case 260 /* NamespaceExportDeclaration */: - return emitNamespaceExportDeclaration(node); - case 261 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 262 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 263 /* ImportClause */: - return emitImportClause(node); - case 264 /* NamespaceImport */: - return emitNamespaceImport(node); - case 265 /* NamedImports */: - return emitNamedImports(node); - case 266 /* ImportSpecifier */: - return emitImportSpecifier(node); - case 267 /* ExportAssignment */: - return emitExportAssignment(node); - case 268 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 269 /* NamedExports */: - return emitNamedExports(node); - case 270 /* NamespaceExport */: - return emitNamespaceExport(node); - case 271 /* ExportSpecifier */: - return emitExportSpecifier(node); - case 272 /* MissingDeclaration */: - return; - // Module references - case 273 /* ExternalModuleReference */: - return emitExternalModuleReference(node); - // JSX - case 274 /* JsxElement */: - return emitJsxElement(node); - case 275 /* JsxSelfClosingElement */: - return emitJsxSelfClosingElement(node); - case 278 /* JsxFragment */: - return emitJsxFragment(node); - case 276 /* JsxOpeningElement */: - case 279 /* JsxOpeningFragment */: - return emitJsxOpeningElementOrFragment(node); - case 277 /* JsxClosingElement */: - case 280 /* JsxClosingFragment */: - return emitJsxClosingElementOrFragment(node); - case 281 /* JsxAttribute */: - return emitJsxAttribute(node); - case 282 /* JsxAttributes */: - return emitJsxAttributes(node); - case 283 /* JsxSpreadAttribute */: - return emitJsxSpreadAttribute(node); - case 284 /* JsxExpression */: - return emitJsxExpression(node); - // Clauses - case 285 /* CaseClause */: - return emitCaseClause(node); - case 286 /* DefaultClause */: - return emitDefaultClause(node); - case 287 /* HeritageClause */: - return emitHeritageClause(node); - case 288 /* CatchClause */: - return emitCatchClause(node); - // Property assignments - case 289 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 290 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 291 /* SpreadAssignment */: - return emitSpreadAssignment(node); - // Enum - case 292 /* EnumMember */: - return emitEnumMember(node); - // Unparsed - case 293 /* UnparsedPrologue */: - return writeUnparsedNode(node); - case 300 /* UnparsedSource */: - case 294 /* UnparsedPrepend */: - return emitUnparsedSourceOrPrepend(node); - case 295 /* UnparsedText */: - case 296 /* UnparsedInternalText */: - return emitUnparsedTextLike(node); - case 297 /* UnparsedSyntheticReference */: - return emitUnparsedSyntheticReference(node); - // Top-level nodes - case 298 /* SourceFile */: - return emitSourceFile(node); - case 299 /* Bundle */: - ts.Debug.fail("Bundles should be printed using printBundle"); - break; - // SyntaxKind.UnparsedSource (handled above) - case 301 /* InputFiles */: - ts.Debug.fail("InputFiles should not be printed"); - break; - // JSDoc nodes (only used in codefixes currently) - case 302 /* JSDocTypeExpression */: - return emitJSDocTypeExpression(node); - case 303 /* JSDocNameReference */: - return emitJSDocNameReference(node); - case 304 /* JSDocAllType */: - return writePunctuation("*"); - case 305 /* JSDocUnknownType */: - return writePunctuation("?"); - case 306 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 307 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 308 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 309 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 182 /* RestType */: - case 310 /* JSDocVariadicType */: - return emitRestOrJSDocVariadicType(node); - // SyntaxKind.JSDocNamepathType (missing) - case 312 /* JSDocComment */: - return emitJSDoc(node); - case 314 /* JSDocTypeLiteral */: - return emitJSDocTypeLiteral(node); - case 315 /* JSDocSignature */: - return emitJSDocSignature(node); - case 317 /* JSDocTag */: - case 322 /* JSDocClassTag */: - return emitJSDocSimpleTag(node); - case 318 /* JSDocAugmentsTag */: - case 319 /* JSDocImplementsTag */: - return emitJSDocHeritageTag(node); - // SyntaxKind.JSDocAuthorTag (missing) - // SyntaxKind.JSDocDeprecatedTag (missing) - // SyntaxKind.JSDocClassTag (see JSDocTag, above) - // SyntaxKind.JSDocPublicTag (missing) - // SyntaxKind.JSDocPrivateTag (missing) - // SyntaxKind.JSDocProtectedTag (missing) - // SyntaxKind.JSDocReadonlyTag (missing) - case 328 /* JSDocCallbackTag */: - return emitJSDocCallbackTag(node); - // SyntaxKind.JSDocEnumTag (see below) - case 330 /* JSDocParameterTag */: - case 337 /* JSDocPropertyTag */: - return emitJSDocPropertyLikeTag(node); - case 329 /* JSDocEnumTag */: - case 331 /* JSDocReturnTag */: - case 332 /* JSDocThisTag */: - case 333 /* JSDocTypeTag */: - return emitJSDocSimpleTypedTag(node); - case 334 /* JSDocTemplateTag */: - return emitJSDocTemplateTag(node); - case 335 /* JSDocTypedefTag */: - return emitJSDocTypedefTag(node); - case 336 /* JSDocSeeTag */: - return emitJSDocSeeTag(node); - // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) - // Synthesized list - case 338 /* SyntaxList */: - ts.Debug.fail("SyntaxList should not be printed"); - break; - // Transformation nodes - case 339 /* NotEmittedStatement */: - break; - case 340 /* PartiallyEmittedExpression */: - return emitPartiallyEmittedExpression(node); - case 341 /* CommaListExpression */: - return emitCommaList(node); - case 342 /* MergeDeclarationMarker */: - case 343 /* EndOfDeclarationMarker */: - break; - case 344 /* SyntheticReferenceExpression */: - ts.Debug.fail("SyntheticReferenceExpression should not be printed"); + function pipelineEmitWithHintWorker(hint, node) { + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 6 /* JsxAttributeValue */) + return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + ts.Debug.assertNode(node, ts.isEmptyStatement); + return emitEmptyStatement(/*isEmbeddedStatement*/ true); + } + if (hint === 4 /* Unspecified */) { + switch (node.kind) { + // Pseudo-literals + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return emitLiteral(node, /*jsxAttributeEscape*/ false); + // Identifiers + case 78 /* Identifier */: + return emitIdentifier(node); + // PrivateIdentifiers + case 79 /* PrivateIdentifier */: + return emitPrivateIdentifier(node); + // Parse tree nodes + // Names + case 158 /* QualifiedName */: + return emitQualifiedName(node); + case 159 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 160 /* TypeParameter */: + return emitTypeParameter(node); + case 161 /* Parameter */: + return emitParameter(node); + case 162 /* Decorator */: + return emitDecorator(node); + // Type members + case 163 /* PropertySignature */: + return emitPropertySignature(node); + case 164 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 165 /* MethodSignature */: + return emitMethodSignature(node); + case 166 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 167 /* Constructor */: + return emitConstructor(node); + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 170 /* CallSignature */: + return emitCallSignature(node); + case 171 /* ConstructSignature */: + return emitConstructSignature(node); + case 172 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 173 /* TypePredicate */: + return emitTypePredicate(node); + case 174 /* TypeReference */: + return emitTypeReference(node); + case 175 /* FunctionType */: + return emitFunctionType(node); + case 176 /* ConstructorType */: + return emitConstructorType(node); + case 177 /* TypeQuery */: + return emitTypeQuery(node); + case 178 /* TypeLiteral */: + return emitTypeLiteral(node); + case 179 /* ArrayType */: + return emitArrayType(node); + case 180 /* TupleType */: + return emitTupleType(node); + case 181 /* OptionalType */: + return emitOptionalType(node); + // SyntaxKind.RestType is handled below + case 183 /* UnionType */: + return emitUnionType(node); + case 184 /* IntersectionType */: + return emitIntersectionType(node); + case 185 /* ConditionalType */: + return emitConditionalType(node); + case 186 /* InferType */: + return emitInferType(node); + case 187 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 224 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 188 /* ThisType */: + return emitThisType(); + case 189 /* TypeOperator */: + return emitTypeOperator(node); + case 190 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 191 /* MappedType */: + return emitMappedType(node); + case 192 /* LiteralType */: + return emitLiteralType(node); + case 193 /* NamedTupleMember */: + return emitNamedTupleMember(node); + case 194 /* TemplateLiteralType */: + return emitTemplateType(node); + case 195 /* TemplateLiteralTypeSpan */: + return emitTemplateTypeSpan(node); + case 196 /* ImportType */: + return emitImportTypeNode(node); + // Binding patterns + case 197 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 198 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 199 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 229 /* TemplateSpan */: + return emitTemplateSpan(node); + case 230 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 231 /* Block */: + return emitBlock(node); + case 233 /* VariableStatement */: + return emitVariableStatement(node); + case 232 /* EmptyStatement */: + return emitEmptyStatement(/*isEmbeddedStatement*/ false); + case 234 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 235 /* IfStatement */: + return emitIfStatement(node); + case 236 /* DoStatement */: + return emitDoStatement(node); + case 237 /* WhileStatement */: + return emitWhileStatement(node); + case 238 /* ForStatement */: + return emitForStatement(node); + case 239 /* ForInStatement */: + return emitForInStatement(node); + case 240 /* ForOfStatement */: + return emitForOfStatement(node); + case 241 /* ContinueStatement */: + return emitContinueStatement(node); + case 242 /* BreakStatement */: + return emitBreakStatement(node); + case 243 /* ReturnStatement */: + return emitReturnStatement(node); + case 244 /* WithStatement */: + return emitWithStatement(node); + case 245 /* SwitchStatement */: + return emitSwitchStatement(node); + case 246 /* LabeledStatement */: + return emitLabeledStatement(node); + case 247 /* ThrowStatement */: + return emitThrowStatement(node); + case 248 /* TryStatement */: + return emitTryStatement(node); + case 249 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 250 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 251 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 252 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 253 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 254 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 255 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 256 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 257 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 258 /* ModuleBlock */: + return emitModuleBlock(node); + case 259 /* CaseBlock */: + return emitCaseBlock(node); + case 260 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 261 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 262 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 263 /* ImportClause */: + return emitImportClause(node); + case 264 /* NamespaceImport */: + return emitNamespaceImport(node); + case 270 /* NamespaceExport */: + return emitNamespaceExport(node); + case 265 /* NamedImports */: + return emitNamedImports(node); + case 266 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 267 /* ExportAssignment */: + return emitExportAssignment(node); + case 268 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 269 /* NamedExports */: + return emitNamedExports(node); + case 271 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 272 /* MissingDeclaration */: + return; + // Module references + case 273 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 11 /* JsxText */: + return emitJsxText(node); + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 277 /* JsxClosingElement */: + case 280 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 281 /* JsxAttribute */: + return emitJsxAttribute(node); + case 282 /* JsxAttributes */: + return emitJsxAttributes(node); + case 283 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 284 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 285 /* CaseClause */: + return emitCaseClause(node); + case 286 /* DefaultClause */: + return emitDefaultClause(node); + case 287 /* HeritageClause */: + return emitHeritageClause(node); + case 288 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 289 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 290 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 291 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 292 /* EnumMember */: + return emitEnumMember(node); + // Unparsed + case 293 /* UnparsedPrologue */: + return writeUnparsedNode(node); + case 300 /* UnparsedSource */: + case 294 /* UnparsedPrepend */: + return emitUnparsedSourceOrPrepend(node); + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: + return emitUnparsedTextLike(node); + case 297 /* UnparsedSyntheticReference */: + return emitUnparsedSyntheticReference(node); + // Top-level nodes + case 298 /* SourceFile */: + return emitSourceFile(node); + case 299 /* Bundle */: + return ts.Debug.fail("Bundles should be printed using printBundle"); + // SyntaxKind.UnparsedSource (handled above) + case 301 /* InputFiles */: + return ts.Debug.fail("InputFiles should not be printed"); + // JSDoc nodes (only used in codefixes currently) + case 302 /* JSDocTypeExpression */: + return emitJSDocTypeExpression(node); + case 303 /* JSDocNameReference */: + return emitJSDocNameReference(node); + case 304 /* JSDocAllType */: + return writePunctuation("*"); + case 305 /* JSDocUnknownType */: + return writePunctuation("?"); + case 306 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 307 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 308 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 309 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 182 /* RestType */: + case 310 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + case 311 /* JSDocNamepathType */: + return; + case 312 /* JSDocComment */: + return emitJSDoc(node); + case 314 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 315 /* JSDocSignature */: + return emitJSDocSignature(node); + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + return emitJSDocSimpleTag(node); + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + return emitJSDocHeritageTag(node); + case 320 /* JSDocAuthorTag */: + case 321 /* JSDocDeprecatedTag */: + return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 327 /* JSDocOverrideTag */: + return; + case 328 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + // SyntaxKind.JSDocEnumTag (see below) + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 329 /* JSDocEnumTag */: + case 331 /* JSDocReturnTag */: + case 332 /* JSDocThisTag */: + case 333 /* JSDocTypeTag */: + return emitJSDocSimpleTypedTag(node); + case 334 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 335 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 336 /* JSDocSeeTag */: + return emitJSDocSeeTag(node); + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) + // Transformation nodes + case 339 /* NotEmittedStatement */: + case 343 /* EndOfDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: + return; + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + if (substituteNode !== ts.noEmitSubstitution) { + var substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } + } + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node, /*jsxAttributeEscape*/ false); + // Identifiers + case 78 /* Identifier */: + return emitIdentifier(node); + // Expressions + case 200 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 201 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 202 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 203 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 204 /* CallExpression */: + return emitCallExpression(node); + case 205 /* NewExpression */: + return emitNewExpression(node); + case 206 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 207 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 208 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 209 /* FunctionExpression */: + return emitFunctionExpression(node); + case 210 /* ArrowFunction */: + return emitArrowFunction(node); + case 211 /* DeleteExpression */: + return emitDeleteExpression(node); + case 212 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 213 /* VoidExpression */: + return emitVoidExpression(node); + case 214 /* AwaitExpression */: + return emitAwaitExpression(node); + case 215 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 216 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 217 /* BinaryExpression */: + return emitBinaryExpression(node); + case 218 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 219 /* TemplateExpression */: + return emitTemplateExpression(node); + case 220 /* YieldExpression */: + return emitYieldExpression(node); + case 221 /* SpreadElement */: + return emitSpreadElement(node); + case 222 /* ClassExpression */: + return emitClassExpression(node); + case 223 /* OmittedExpression */: + return; + case 225 /* AsExpression */: + return emitAsExpression(node); + case 226 /* NonNullExpression */: + return emitNonNullExpression(node); + case 227 /* MetaProperty */: + return emitMetaProperty(node); + case 228 /* SyntheticExpression */: + return ts.Debug.fail("SyntheticExpression should never be printed."); + // JSX + case 274 /* JsxElement */: + return emitJsxElement(node); + case 275 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 278 /* JsxFragment */: + return emitJsxFragment(node); + // Synthesized list + case 338 /* SyntaxList */: + return ts.Debug.fail("SyntaxList should not be printed"); + // Transformation nodes + case 339 /* NotEmittedStatement */: + return; + case 340 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 341 /* CommaListExpression */: + return emitCommaList(node); + case 342 /* MergeDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: + return; + case 344 /* SyntheticReferenceExpression */: + return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); + } } if (ts.isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); if (ts.isTokenKind(node.kind)) return writeTokenNode(node, writePunctuation); + ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); } function emitMappedTypeParameter(node) { emit(node.name); @@ -103955,6 +104510,13 @@ var ts; writeSpace(); emit(node.constraint); } + function pipelineEmitWithSubstitution(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node); + ts.Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); + } function getHelpersFromBundledSourceFiles(bundle) { var result; if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) { @@ -104057,9 +104619,6 @@ var ts; writeStringLiteral(text); } } - function emitStringLiteralWithJsxAttributeEscape(node) { - emitLiteral(node, /*jsxAttributeEscape*/ true); - } // SyntaxKind.UnparsedSource // SyntaxKind.UnparsedPrepend function emitUnparsedSourceOrPrepend(unparsed) { @@ -104118,7 +104677,7 @@ var ts; } function emitEntityName(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -104126,7 +104685,7 @@ var ts; } function emitComputedPropertyName(node) { writePunctuation("["); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } // @@ -104160,11 +104719,11 @@ 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); + 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); } function emitDecorator(decorator) { writePunctuation("@"); - emit(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } // // Type members @@ -104329,7 +104888,7 @@ var ts; writePunctuation("}"); } function emitArrayType(node) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -104352,21 +104911,21 @@ var ts; emit(node.type); } function emitOptionalType(node) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 516 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node) { - emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -104392,10 +104951,10 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -104418,7 +104977,7 @@ var ts; writeSpace(); } writePunctuation("["); - emitWithContext(node.typeParameter, emitMappedTypeParameter); + pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter); if (node.nameType) { writeSpace(); writeKeyword("as"); @@ -104446,7 +105005,7 @@ var ts; writePunctuation("}"); } function emitLiteralType(node) { - emit(node.literal); + emitExpression(node.literal); } function emitTemplateType(node) { emit(node.head); @@ -104488,7 +105047,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // Expressions @@ -104496,7 +105055,7 @@ var ts; function emitArrayLiteralExpression(node) { var elements = node.elements; var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; - emitList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -104512,7 +105071,7 @@ var ts; } } function emitPropertyAccessExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos); var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); var linesAfterDot = getLinesBetweenNodes(node, token, node.name); @@ -104554,41 +105113,41 @@ var ts; } } function emitElementAccessExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); - emit(node.argumentExpression); + emitExpression(node.argumentExpression); emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitList(node, node.arguments, 2576 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitList(node, node.arguments, 18960 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node) { - emit(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); - emit(node.template); + emitExpression(node.template); } function emitTypeAssertionExpression(node) { writePunctuation("<"); emit(node.type); writePunctuation(">"); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emit(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -104612,29 +105171,29 @@ var ts; function emitDeleteExpression(node) { emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node) { writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emit(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node) { // In some cases, we need to emit a space between the operator and the operand. One obvious case @@ -104655,11 +105214,11 @@ var ts; || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { - emit(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } function createEmitBinaryExpression() { - return ts.createBinaryExpressionTrampoline(onEnter, maybeEmitExpression, onOperator, maybeEmitExpression, onExit, /*foldState*/ undefined); + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); function onEnter(node, state) { if (state) { state.stackIndex++; @@ -104669,7 +105228,12 @@ var ts; state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); - beforeEmitWithContext(node, emitComments_1, emitSourceMaps); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (emitComments_1) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); } else { state = { @@ -104684,6 +105248,9 @@ var ts; } return state; } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } function onOperator(operatorToken, _state, node) { var isCommaOperator = operatorToken.kind !== 27 /* CommaToken */; var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); @@ -104694,6 +105261,9 @@ var ts; emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } function onExit(node, state) { var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); @@ -104705,16 +105275,35 @@ var ts; var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex]; var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex]; - afterEmitWithContext(node, shouldEmitComments_1, shouldEmitSourceMaps_1, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd, savedPreserveSourceNewlines); + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps_1) + emitSourceMapsAfterNode(node); + if (shouldEmitComments_1) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); state.stackIndex--; } } - function maybeEmitExpression(next) { - // Push a new frame for binary expressions, otherwise emit all other expressions. - if (ts.isBinaryExpression(next)) { - return next; + function maybeEmitExpression(next, parent, side) { + var parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); + var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next); + if (pipelinePhase === pipelineEmitWithSubstitution) { + ts.Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression)); + pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next); + lastSubstitution = undefined; } - emit(next); + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (ts.isBinaryExpression(next)) { + return next; + } + } + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1 /* Expression */, next); } } function emitConditionalExpression(node) { @@ -104722,16 +105311,16 @@ var ts; var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emit(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true); - emit(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true); - emit(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { @@ -104741,22 +105330,22 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node) { + function emitSpreadElement(node) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emit(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -104765,7 +105354,7 @@ var ts; } } function emitNonNullExpression(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } function emitMetaProperty(node) { @@ -104777,7 +105366,7 @@ var ts; // Misc // function emitTemplateSpan(node) { - emit(node.expression); + emitExpression(node.expression); emit(node.literal); } // @@ -104807,11 +105396,8 @@ var ts; writeTrailingSemicolon(); } } - function emitEmbeddedEmptyStatement(_node) { - emitEmptyStatement(/*isEmbeddedStatement*/ true); - } function emitExpressionStatement(node) { - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); // Emit semicolon in non json files // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { @@ -104822,7 +105408,7 @@ var ts; var openParenPos = emitTokenWithComment(98 /* IfKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { @@ -104841,7 +105427,7 @@ var ts; var openParenPos = emitTokenWithComment(114 /* WhileKeyword */, startPos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); } function emitDoStatement(node) { @@ -104880,7 +105466,7 @@ var ts; writeSpace(); emitTokenWithComment(100 /* InKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -104893,7 +105479,7 @@ var ts; writeSpace(); emitTokenWithComment(157 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -104903,7 +105489,7 @@ var ts; emit(node); } else { - emit(node); + emitExpression(node); } } } @@ -104950,7 +105536,7 @@ var ts; var openParenPos = emitTokenWithComment(115 /* WithKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.statement); } @@ -104958,7 +105544,7 @@ var ts; var openParenPos = emitTokenWithComment(106 /* SwitchKeyword */, node.pos, writeKeyword, node); writeSpace(); emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); writeSpace(); emit(node.caseBlock); @@ -105000,7 +105586,7 @@ var ts; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); @@ -105016,7 +105602,7 @@ var ts; writeKeyword("function"); emit(node.asteriskToken); writeSpace(); - emit(node.name); + emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } function emitSignatureAndBody(node, emitSignatureHead) { @@ -105040,7 +105626,7 @@ var ts; else { emitSignatureHead(node); writeSpace(); - emit(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -105115,7 +105701,7 @@ var ts; increaseIndent(); } else { - emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, /*parenthesizerRule*/ undefined, statementOffset); } } function emitClassDeclaration(node) { @@ -105128,7 +105714,7 @@ var ts; writeKeyword("class"); if (node.name) { writeSpace(); - emit(node.name); + emitIdentifierName(node.name); } var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { @@ -105226,7 +105812,7 @@ var ts; } function emitModuleReference(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -105242,7 +105828,7 @@ var ts; emitTokenWithComment(153 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } - emit(node.moduleSpecifier); + emitExpression(node.moduleSpecifier); writeTrailingSemicolon(); } function emitImportClause(node) { @@ -105280,7 +105866,9 @@ var ts; emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); - emit(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(62 /* EqualsToken */) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -105301,7 +105889,7 @@ var ts; var fromPos = node.exportClause ? node.exportClause.end : nextPos; emitTokenWithComment(153 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); - emit(node.moduleSpecifier); + emitExpression(node.moduleSpecifier); } writeTrailingSemicolon(); } @@ -105348,7 +105936,7 @@ var ts; function emitExternalModuleReference(node) { writeKeyword("require"); writePunctuation("("); - emit(node.expression); + emitExpression(node.expression); writePunctuation(")"); } // @@ -105400,17 +105988,13 @@ var ts; function emitJsxAttributes(node) { emitList(node, node.properties, 262656 /* JsxElementAttributes */); } - function emitJsxAttributeValue(node) { - var emitCallback = ts.isStringLiteral(node) ? emitStringLiteralWithJsxAttributeEscape : emitWorker; - emitWithContext(node, emitCallback); - } function emitJsxAttribute(node) { emit(node.name); emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue); } function emitJsxSpreadAttribute(node) { writePunctuation("{..."); - emit(node.expression); + emitExpression(node.expression); writePunctuation("}"); } function hasTrailingCommentsAtPosition(pos) { @@ -105435,7 +106019,7 @@ var ts; } var end = emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); emit(node.dotDotDotToken); - emit(node.expression); + emitExpression(node.expression); emitTokenWithComment(19 /* CloseBraceToken */, ((_a = node.expression) === null || _a === void 0 ? void 0 : _a.end) || end, writePunctuation, node); if (isMultiline) { writer.decreaseIndent(); @@ -105444,7 +106028,7 @@ var ts; } function emitJsxTagName(node) { if (node.kind === 78 /* Identifier */) { - emit(node); + emitExpression(node); } else { emit(node); @@ -105456,7 +106040,7 @@ var ts; function emitCaseClause(node) { emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { @@ -105517,7 +106101,7 @@ var ts; var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emit(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node) { emit(node.name); @@ -105525,13 +106109,13 @@ var ts; writeSpace(); writePunctuation("="); writeSpace(); - emit(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node) { if (node.expression) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emit(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } // @@ -105539,7 +106123,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // JSDoc @@ -105784,15 +106368,15 @@ var ts; emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + emitList(node, statements, 1 /* MultiLine */, /*parenthesizerRule*/ undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } // Transformation nodes function emitPartiallyEmittedExpression(node) { - emit(node.expression); + emitExpression(node.expression); } function emitCommaList(node) { - emitList(node, node.elements, 528 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -105938,12 +106522,12 @@ var ts; emit(node); } } - function emitInitializer(node, equalCommentStartPos, container) { + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); - emit(node); + emitExpression(node, parenthesizerRule); } } function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { @@ -105958,10 +106542,10 @@ var ts; emit(node); } } - function emitExpressionWithLeadingSpace(node) { + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { if (node) { writeSpace(); - emit(node); + emitExpression(node, parenthesizerRule); } } function emitWithTrailingSpace(node) { @@ -105979,7 +106563,7 @@ var ts; writeLine(); increaseIndent(); if (ts.isEmptyStatement(node)) { - emitWithContext(node, emitEmbeddedEmptyStatement); + pipelineEmit(5 /* EmbeddedStatement */, node); } else { emit(node); @@ -105991,7 +106575,7 @@ var ts; emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures @@ -106052,7 +106636,13 @@ var ts; break; } } - function emitList(parentNode, children, format, start, count) { + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; @@ -106156,7 +106746,12 @@ var ts; shouldEmitInterveningComments = mayEmitInterveningComments; } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); shouldDecreaseIndentAfterEmit = false; @@ -106892,6 +107487,33 @@ var ts; return node; } // Comments + function pipelineEmitWithComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit leading comments + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit trailing comments + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; @@ -107187,6 +107809,50 @@ var ts; } return node.parsedSourceMap || undefined; } + function pipelineEmitWithSourceMaps(hint, node) { + var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node); + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit leading sourcemap + if (ts.isUnparsedNode(node)) { + ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); + var parsed = getParsedSourceMap(node.parent); + if (parsed && sourceMapGenerator) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); + } + } + else { + var source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 339 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + } + } + } + function emitSourceMapsAfterNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit trailing sourcemap + if (!ts.isUnparsedNode(node)) { + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = false; + } + if (node.kind !== 339 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); + } + } + } /** * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source */ @@ -107279,736 +107945,6 @@ var ts; } } ts.createPrinter = createPrinter; - var PreprintPipelinePhase; - (function (PreprintPipelinePhase) { - PreprintPipelinePhase[PreprintPipelinePhase["Notification"] = 0] = "Notification"; - PreprintPipelinePhase[PreprintPipelinePhase["Substitution"] = 1] = "Substitution"; - PreprintPipelinePhase[PreprintPipelinePhase["Visit"] = 2] = "Visit"; - })(PreprintPipelinePhase || (PreprintPipelinePhase = {})); - function createPreprinter(handlers) { - var _a = handlers.substituteNode, substituteNode = _a === void 0 ? ts.noEmitSubstitution : _a, _b = handlers.onEmitNode, onEmitNode = _b === void 0 ? ts.noEmitNotification : _b, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled; - var pipelineResult; - // Outer visitors - // - // These visitors are invoked by inner visitors to re-enter the pipeline - // for notification and substitution. - var visit = makeVisitor(pipelineVisitorForUnspecified); - var visitSourceFile = makeVisitor(pipelineVisitorForSourceFile, ts.isSourceFile); - var visitIdentifierName = makeVisitor(pipelineVisitorForIdentifierName, ts.isIdentifier); - var visitModuleName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isModuleName); - var visitPropertyName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isPropertyName); - var visitMemberName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isMemberName); - var visitBindingName = makeVisitor(pipelineVisitorForIdentifierNameOrUnspecified, ts.isBindingName); - var visitEntityName = makeVisitor(pipelineVisitorForIdentifierReferenceOrUnspecified, ts.isEntityName); - var visitExpression = makeVisitor(pipelineVisitorForExpression, ts.isExpression); - var visitForInitializer = makeVisitor(pipelineVisitorForForInitializer, ts.isForInitializer); - var visitTypeNode = makeVisitor(pipelineVisitorForUnspecified, ts.isTypeNode); - var visitEmbeddedStatement = makeVisitor(pipelineVisitorForEmbeddedStatement, ts.isStatement, ts.factory.liftToBlock); - var visitJsxAttributeValue = makeVisitor(pipelineVisitorForJsxAttributeValue, ts.isStringLiteralOrJsxExpression); - var visitMappedTypeParameter = makeVisitor(pipelineVisitorForMappedTypeParameter, ts.isTypeParameterDeclaration); - var visitConciseBody = makeVisitor(pipelineVisitorForConciseBody, ts.isConciseBody); - var visitFunctionBody = makeVisitor(pipelineVisitorForUnspecified, ts.isFunctionBody); - var visitList = makeListVisitor(pipelineVisitorForUnspecified); - var visitTypeNodeList = makeListVisitor(pipelineVisitorForUnspecified, ts.isTypeNode); - var visitExpressionList = makeListVisitor(pipelineVisitorForExpression, ts.isExpression); - var visitParameterList = makeListVisitor(pipelineVisitorForUnspecified, ts.isParameter); - function makeVisitor(outerVisitor, defaultTest, lift) { - function visit(node, test) { - return ts.visitNode(node, outerVisitor, test || defaultTest, lift); - } - return visit; - } - function makeListVisitor(outerVisitor, defaultTest) { - function visitList(nodes, test) { - if (test === void 0) { test = defaultTest || ts.returnTrue; } - return ts.visitNodes(nodes, outerVisitor, test); - } - return visitList; - } - // Pipeline Visitors - // - // These visitors execute our existing pipeline logic for notification and substitution, - // but adapted to our visitor pattern. In some cases, we refine the `EmitHint` we pass - // to the `onEmitNode` and `substituteNode` APIs to ensure they receive the appropriate - // context. - // - // For example, the ConciseBody of an arrow function could be an Identifier, in which - // case we would want to use `EmitHint.Expression` to ensure we treat the identifier - // as an expression during substitution. - function pipelineVisitorForSourceFile(node) { return pipelineVisitorWorker(0 /* SourceFile */, node); } - function pipelineVisitorForExpression(node) { return pipelineVisitorWorker(1 /* Expression */, node); } - function pipelineVisitorForIdentifierName(node) { return pipelineVisitorWorker(2 /* IdentifierName */, node); } - function pipelineVisitorForIdentifierNameOrUnspecified(node) { return pipelineVisitorWorker(ts.isIdentifier(node) ? 2 /* IdentifierName */ : 4 /* Unspecified */, node); } - function pipelineVisitorForIdentifierReferenceOrUnspecified(node) { return pipelineVisitorWorker(ts.isIdentifier(node) ? 1 /* Expression */ : 4 /* Unspecified */, node); } - function pipelineVisitorForForInitializer(node) { return pipelineVisitorWorker(ts.isVariableDeclarationList(node) ? 4 /* Unspecified */ : 1 /* Expression */, node); } - function pipelineVisitorForMappedTypeParameter(node) { return pipelineVisitorWorker(3 /* MappedTypeParameter */, node); } - function pipelineVisitorForEmbeddedStatement(node) { return pipelineVisitorWorker(ts.isEmptyStatement(node) ? 5 /* EmbeddedStatement */ : 4 /* Unspecified */, node); } - function pipelineVisitorForJsxAttributeValue(node) { return pipelineVisitorWorker(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); } - function pipelineVisitorForConciseBody(node) { return pipelineVisitorWorker(ts.isBlock(node) ? 4 /* Unspecified */ : 1 /* Expression */, node); } - function pipelineVisitorForUnspecified(node) { return pipelineVisitorWorker(4 /* Unspecified */, node); } - /** - * Adapts the emit pipeline API to work with the visitor API - */ - function pipelineVisitorWorker(hint, node) { - resetPipelineResult(); - // Get the first supported pipeline phase for this node and evaluate it. We can skip several stack - // frames if we aren't doing emit notification, so we check for substitution and direct callbacks - // and execute those immediately. - var pipelinePhase = getPipelinePhase(0 /* Notification */, node); - if (pipelinePhase === pipelineVisitDirect) { - return visitor(hint, node); - } - if (pipelinePhase === pipelineVisitWithSubstitution) { - // The next phase after substitution is always direct visitation, so we can reduce the call stack - // depth by calling the visitor directly. - return visitor(hint, substituteNode(hint, node)); - } - pipelinePhase(hint, node); - ts.Debug.assertIsDefined(pipelineResult); - var result = pipelineResult; - resetPipelineResult(); - return result; - } - function resetPipelineResult() { - pipelineResult = undefined; - } - /** - * Gets the pipeline callback to pass to the relevant API (i.e., `substituteNode` or `onEmitNode`) - */ - function getPipelinePhase(phase, node) { - switch (phase) { - case 0 /* Notification */: - if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { - return pipelineVisitWithNotification; - } - // falls through - case 1 /* Substitution */: - if (substituteNode !== ts.noEmitSubstitution) { - return pipelineVisitWithSubstitution; - } - // falls through - default: - return pipelineVisitDirect; - } - } - /** - * A callback that can be evaluated to trigger emit notification as part of the emit pipeline. - */ - function pipelineVisitWithNotification(hint, node) { - onEmitNode(hint, node, getPipelinePhase(1 /* Substitution */, node)); - } - /** - * A callback that can be evaluated to trigger JIT substitution as part of the emit pipeline. - */ - function pipelineVisitWithSubstitution(hint, node) { - // Next phase is always direct visitation, so we can reduce the call stack - // depth by calling the visitor directly. - pipelineResult = visitor(hint, substituteNode(hint, node)); - } - /** - * A callback that can be evaluated to visit the subtree of a node. - */ - function pipelineVisitDirect(hint, node) { - pipelineResult = visitor(hint, node); - } - /** - * Re-enters the visitor pattern from the pipeline pattern to perform - * tree updates and trigger parenthesization rules. - */ - function visitor(hint, node) { - // This should align with the assertions in `pipelineEmitWithHint`. - if (hint === 0 /* SourceFile */) - return preprintSourceFile(ts.cast(node, ts.isSourceFile)); - if (hint === 2 /* IdentifierName */) - return preprintIdentifier(ts.cast(node, ts.isIdentifier)); - if (hint === 6 /* JsxAttributeValue */) - return ts.cast(node, ts.isStringLiteral); - if (hint === 3 /* MappedTypeParameter */) - return preprintTypeParameterDeclaration(ts.cast(node, ts.isTypeParameterDeclaration)); - if (hint === 5 /* EmbeddedStatement */) - return ts.cast(node, ts.isEmptyStatement); - var kind = node.kind; - // No need to visit nodes without children. - if ((kind > 0 /* FirstToken */ && kind <= 157 /* LastToken */) || kind === 188 /* ThisType */) { - return node; - } - if (hint === 4 /* Unspecified */) { - if (ts.isKeyword(node.kind)) - return node; - switch (node.kind) { - // Identifiers - case 78 /* Identifier */: - return preprintIdentifier(node); - // Names - case 158 /* QualifiedName */: - ts.Debug.type(node); - return ts.factory.updateQualifiedName(node, visitEntityName(node.left), visitIdentifierName(node.right)); - case 159 /* ComputedPropertyName */: - ts.Debug.type(node); - return ts.factory.updateComputedPropertyName(node, visitExpression(node.expression)); - // Signature elements - case 160 /* TypeParameter */: - return preprintTypeParameterDeclaration(node); - case 161 /* Parameter */: - ts.Debug.type(node); - return ts.factory.updateParameterDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.dotDotDotToken, ts.isDotDotDotToken), visitBindingName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 162 /* Decorator */: - ts.Debug.type(node); - return ts.factory.updateDecorator(node, visitExpression(node.expression)); - // Type members - case 163 /* PropertySignature */: - ts.Debug.type(node); - return ts.factory.updatePropertySignature(node, visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type)); - case 164 /* PropertyDeclaration */: - ts.Debug.type(node); - return ts.factory.updatePropertyDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken || node.exclamationToken, ts.isQuestionOrExclamationToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 165 /* MethodSignature */: - ts.Debug.type(node); - return ts.factory.updateMethodSignature(node, visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 166 /* MethodDeclaration */: - ts.Debug.type(node); - return ts.factory.updateMethodDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitPropertyName(node.name), visit(node.questionToken, ts.isQuestionToken), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 167 /* Constructor */: - ts.Debug.type(node); - return ts.factory.updateConstructorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitParameterList(node.parameters), visitFunctionBody(node.body)); - case 168 /* GetAccessor */: - ts.Debug.type(node); - return ts.factory.updateGetAccessorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 169 /* SetAccessor */: - ts.Debug.type(node); - return ts.factory.updateSetAccessorDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitPropertyName(node.name), visitParameterList(node.parameters), visitFunctionBody(node.body)); - case 170 /* CallSignature */: - ts.Debug.type(node); - return ts.factory.updateCallSignature(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 171 /* ConstructSignature */: - ts.Debug.type(node); - return ts.factory.updateConstructSignature(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 172 /* IndexSignature */: - ts.Debug.type(node); - return ts.factory.updateIndexSignature(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitParameterList(node.parameters), visitTypeNode(node.type)); - // Types - case 173 /* TypePredicate */: - ts.Debug.type(node); - return ts.factory.updateTypePredicateNode(node, visit(node.assertsModifier, ts.isAssertsKeyword), visit(node.parameterName, ts.isIdentifierOrThisTypeNode), visitTypeNode(node.type)); - case 174 /* TypeReference */: - ts.Debug.type(node); - return ts.factory.updateTypeReferenceNode(node, visitEntityName(node.typeName), visitTypeNodeList(node.typeArguments)); - case 175 /* FunctionType */: - ts.Debug.type(node); - return ts.factory.updateFunctionTypeNode(node, visitList(node.typeParameters, ts.isTypeParameterDeclaration), ts.visitNodes(node.parameters, pipelineVisitorForUnspecified, ts.isParameterDeclaration), visitTypeNode(node.type)); - case 176 /* ConstructorType */: - ts.Debug.type(node); - return ts.factory.updateConstructorTypeNode(node, ts.visitNodes(node.modifiers, pipelineVisitorForUnspecified, ts.isModifier), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type)); - case 177 /* TypeQuery */: - ts.Debug.type(node); - return ts.factory.updateTypeQueryNode(node, visitEntityName(node.exprName)); - case 178 /* TypeLiteral */: - ts.Debug.type(node); - return ts.factory.updateTypeLiteralNode(node, visitList(node.members, ts.isTypeElement)); - case 179 /* ArrayType */: - ts.Debug.type(node); - return ts.factory.updateArrayTypeNode(node, visitTypeNode(node.elementType)); - case 180 /* TupleType */: - ts.Debug.type(node); - return ts.factory.updateTupleTypeNode(node, visitTypeNodeList(node.elements)); - case 181 /* OptionalType */: - ts.Debug.type(node); - return ts.factory.updateOptionalTypeNode(node, visitTypeNode(node.type)); - case 182 /* RestType */: - ts.Debug.type(node); - return ts.factory.updateRestTypeNode(node, visitTypeNode(node.type)); - case 183 /* UnionType */: - ts.Debug.type(node); - return ts.factory.updateUnionTypeNode(node, visitTypeNodeList(node.types)); - case 184 /* IntersectionType */: - ts.Debug.type(node); - return ts.factory.updateIntersectionTypeNode(node, visitTypeNodeList(node.types)); - case 185 /* ConditionalType */: - ts.Debug.type(node); - return ts.factory.updateConditionalTypeNode(node, visitTypeNode(node.checkType), visitTypeNode(node.extendsType), visitTypeNode(node.trueType), visitTypeNode(node.falseType)); - case 186 /* InferType */: - ts.Debug.type(node); - return ts.factory.updateInferTypeNode(node, visit(node.typeParameter, ts.isTypeParameterDeclaration)); - case 196 /* ImportType */: - ts.Debug.type(node); - return ts.factory.updateImportTypeNode(node, visitTypeNode(node.argument), visitEntityName(node.qualifier), visitTypeNodeList(node.typeArguments), node.isTypeOf); - case 193 /* NamedTupleMember */: - ts.Debug.type(node); - return ts.factory.updateNamedTupleMember(node, visit(node.dotDotDotToken, ts.isDotDotDotToken), visitIdentifierName(node.name), visit(node.questionToken, ts.isQuestionToken), visitTypeNode(node.type)); - case 187 /* ParenthesizedType */: - ts.Debug.type(node); - return ts.factory.updateParenthesizedType(node, visitTypeNode(node.type)); - case 224 /* ExpressionWithTypeArguments */: - ts.Debug.type(node); - return ts.factory.updateExpressionWithTypeArguments(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments)); - case 189 /* TypeOperator */: - ts.Debug.type(node); - return ts.factory.updateTypeOperatorNode(node, visitTypeNode(node.type)); - case 190 /* IndexedAccessType */: - ts.Debug.type(node); - return ts.factory.updateIndexedAccessTypeNode(node, visitTypeNode(node.objectType), visitTypeNode(node.indexType)); - case 191 /* MappedType */: - ts.Debug.type(node); - return ts.factory.updateMappedTypeNode(node, visit(node.readonlyToken, ts.isReadonlyKeywordOrPlusOrMinusToken), visitMappedTypeParameter(node.typeParameter), visitTypeNode(node.nameType), visit(node.questionToken, ts.isQuestionOrPlusOrMinusToken), visitTypeNode(node.type)); - case 192 /* LiteralType */: - ts.Debug.type(node); - return ts.factory.updateLiteralTypeNode(node, visitExpression(node.literal, ts.isLiteralTypeLikeExpression)); - case 194 /* TemplateLiteralType */: - ts.Debug.type(node); - return ts.factory.updateTemplateLiteralType(node, visit(node.head, ts.isTemplateHead), visitList(node.templateSpans, ts.isTemplateLiteralTypeSpan)); - case 195 /* TemplateLiteralTypeSpan */: - ts.Debug.type(node); - return ts.factory.updateTemplateLiteralTypeSpan(node, visitTypeNode(node.type), visit(node.literal, ts.isTemplateMiddleOrTemplateTail)); - // Binding patterns - case 197 /* ObjectBindingPattern */: - ts.Debug.type(node); - return ts.factory.updateObjectBindingPattern(node, visitList(node.elements, ts.isBindingElement)); - case 198 /* ArrayBindingPattern */: - ts.Debug.type(node); - return ts.factory.updateArrayBindingPattern(node, visitList(node.elements, ts.isArrayBindingElement)); - case 199 /* BindingElement */: - ts.Debug.type(node); - return ts.factory.updateBindingElement(node, visit(node.dotDotDotToken, ts.isDotDotDotToken), visitPropertyName(node.propertyName), visitBindingName(node.name), visitExpression(node.initializer)); - // Misc - case 229 /* TemplateSpan */: - ts.Debug.type(node); - return ts.factory.updateTemplateSpan(node, visitExpression(node.expression), visit(node.literal, ts.isTemplateMiddleOrTemplateTail)); - // Element - case 231 /* Block */: - ts.Debug.type(node); - return ts.factory.updateBlock(node, visitList(node.statements, ts.isStatement)); - case 233 /* VariableStatement */: - ts.Debug.type(node); - return ts.factory.updateVariableStatement(node, visitList(node.modifiers, ts.isModifier), visit(node.declarationList, ts.isVariableDeclarationList)); - case 234 /* ExpressionStatement */: - ts.Debug.type(node); - return ts.factory.updateExpressionStatement(node, visitExpression(node.expression)); - case 235 /* IfStatement */: - ts.Debug.type(node); - return ts.factory.updateIfStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.thenStatement), visitEmbeddedStatement(node.elseStatement)); - case 236 /* DoStatement */: - ts.Debug.type(node); - return ts.factory.updateDoStatement(node, visitEmbeddedStatement(node.statement), visitExpression(node.expression)); - case 237 /* WhileStatement */: - ts.Debug.type(node); - return ts.factory.updateWhileStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 238 /* ForStatement */: - ts.Debug.type(node); - return ts.factory.updateForStatement(node, visitForInitializer(node.initializer), visitExpression(node.condition), visitExpression(node.incrementor), visitEmbeddedStatement(node.statement)); - case 239 /* ForInStatement */: - ts.Debug.type(node); - return ts.factory.updateForInStatement(node, visitForInitializer(node.initializer), visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 240 /* ForOfStatement */: - ts.Debug.type(node); - return ts.factory.updateForOfStatement(node, visit(node.awaitModifier, ts.isAwaitKeyword), visitForInitializer(node.initializer), visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 241 /* ContinueStatement */: - ts.Debug.type(node); - return ts.factory.updateContinueStatement(node, visitIdentifierName(node.label)); - case 242 /* BreakStatement */: - ts.Debug.type(node); - return ts.factory.updateBreakStatement(node, visitIdentifierName(node.label)); - case 243 /* ReturnStatement */: - ts.Debug.type(node); - return ts.factory.updateReturnStatement(node, visitExpression(node.expression)); - case 244 /* WithStatement */: - ts.Debug.type(node); - return ts.factory.updateWithStatement(node, visitExpression(node.expression), visitEmbeddedStatement(node.statement)); - case 245 /* SwitchStatement */: - ts.Debug.type(node); - return ts.factory.updateSwitchStatement(node, visitExpression(node.expression), visit(node.caseBlock, ts.isCaseBlock)); - case 246 /* LabeledStatement */: - ts.Debug.type(node); - return ts.factory.updateLabeledStatement(node, visitIdentifierName(node.label), visitEmbeddedStatement(node.statement)); - case 247 /* ThrowStatement */: - ts.Debug.type(node); - return ts.factory.updateThrowStatement(node, visitExpression(node.expression)); - case 248 /* TryStatement */: - ts.Debug.type(node); - return ts.factory.updateTryStatement(node, visit(node.tryBlock, ts.isBlock), visit(node.catchClause, ts.isCatchClause), visit(node.finallyBlock, ts.isBlock)); - // Declarations - case 250 /* VariableDeclaration */: - ts.Debug.type(node); - return ts.factory.updateVariableDeclaration(node, visitBindingName(node.name), visit(node.exclamationToken, ts.isExclamationToken), visitTypeNode(node.type), visitExpression(node.initializer)); - case 251 /* VariableDeclarationList */: - ts.Debug.type(node); - return ts.factory.updateVariableDeclarationList(node, visitList(node.declarations, ts.isVariableDeclaration)); - case 252 /* FunctionDeclaration */: - ts.Debug.type(node); - return ts.factory.updateFunctionDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 253 /* ClassDeclaration */: - ts.Debug.type(node); - return ts.factory.updateClassDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isClassElement)); - case 254 /* InterfaceDeclaration */: - ts.Debug.type(node); - return ts.factory.updateInterfaceDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isTypeElement)); - case 255 /* TypeAliasDeclaration */: - ts.Debug.type(node); - return ts.factory.updateTypeAliasDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitTypeNode(node.type)); - case 256 /* EnumDeclaration */: - ts.Debug.type(node); - return ts.factory.updateEnumDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.members, ts.isEnumMember)); - case 257 /* ModuleDeclaration */: - ts.Debug.type(node); - return ts.factory.updateModuleDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitModuleName(node.name), visit(node.body, ts.isModuleBody)); - case 258 /* ModuleBlock */: - ts.Debug.type(node); - return ts.factory.updateModuleBlock(node, visitList(node.statements, ts.isStatement)); - case 259 /* CaseBlock */: - ts.Debug.type(node); - return ts.factory.updateCaseBlock(node, visitList(node.clauses, ts.isCaseOrDefaultClause)); - case 260 /* NamespaceExportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateNamespaceExportDeclaration(node, visitIdentifierName(node.name)); - case 261 /* ImportEqualsDeclaration */: - ts.Debug.type(node); - return ts.factory.updateImportEqualsDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), node.isTypeOnly, visitIdentifierName(node.name), visit(node.moduleReference, ts.isModuleReference)); - case 262 /* ImportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateImportDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visit(node.importClause, ts.isImportClause), visitExpression(node.moduleSpecifier)); - case 263 /* ImportClause */: - ts.Debug.type(node); - return ts.factory.updateImportClause(node, node.isTypeOnly, visitIdentifierName(node.name), visit(node.namedBindings, ts.isNamedImportBindings)); - case 264 /* NamespaceImport */: - ts.Debug.type(node); - return ts.factory.updateNamespaceImport(node, visitIdentifierName(node.name)); - case 270 /* NamespaceExport */: - ts.Debug.type(node); - return ts.factory.updateNamespaceExport(node, visitIdentifierName(node.name)); - case 265 /* NamedImports */: - ts.Debug.type(node); - return ts.factory.updateNamedImports(node, visitList(node.elements, ts.isImportSpecifier)); - case 266 /* ImportSpecifier */: - ts.Debug.type(node); - return ts.factory.updateImportSpecifier(node, visitIdentifierName(node.propertyName), visitIdentifierName(node.name)); - case 267 /* ExportAssignment */: - ts.Debug.type(node); - return ts.factory.updateExportAssignment(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitExpression(node.expression)); - case 268 /* ExportDeclaration */: - ts.Debug.type(node); - return ts.factory.updateExportDeclaration(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), node.isTypeOnly, visit(node.exportClause, ts.isNamedExportBindings), visitExpression(node.moduleSpecifier)); - case 269 /* NamedExports */: - ts.Debug.type(node); - return ts.factory.updateNamedExports(node, visitList(node.elements, ts.isExportSpecifier)); - case 271 /* ExportSpecifier */: - ts.Debug.type(node); - return ts.factory.updateExportSpecifier(node, visitIdentifierName(node.propertyName), visitIdentifierName(node.name)); - case 272 /* MissingDeclaration */: - return node; - // Module references - case 273 /* ExternalModuleReference */: - ts.Debug.type(node); - return ts.factory.updateExternalModuleReference(node, visitExpression(node.expression)); - // JSX (non-expression) - case 276 /* JsxOpeningElement */: - ts.Debug.type(node); - return ts.factory.updateJsxOpeningElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression), visitList(node.typeArguments, ts.isTypeNode), visit(node.attributes, ts.isJsxAttributes)); - case 277 /* JsxClosingElement */: - ts.Debug.type(node); - return ts.factory.updateJsxClosingElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression)); - case 281 /* JsxAttribute */: - ts.Debug.type(node); - return ts.factory.updateJsxAttribute(node, visitIdentifierName(node.name), visitJsxAttributeValue(node.initializer)); - case 282 /* JsxAttributes */: - ts.Debug.type(node); - return ts.factory.updateJsxAttributes(node, visitList(node.properties, ts.isJsxAttributeLike)); - case 283 /* JsxSpreadAttribute */: - ts.Debug.type(node); - return ts.factory.updateJsxSpreadAttribute(node, visitExpression(node.expression)); - case 284 /* JsxExpression */: - ts.Debug.type(node); - return ts.factory.updateJsxExpression(node, visitExpression(node.expression)); - // Clauses - case 285 /* CaseClause */: - ts.Debug.type(node); - return ts.factory.updateCaseClause(node, visitExpression(node.expression), visitList(node.statements, ts.isStatement)); - case 286 /* DefaultClause */: - ts.Debug.type(node); - return ts.factory.updateDefaultClause(node, visitList(node.statements, ts.isStatement)); - case 287 /* HeritageClause */: - ts.Debug.type(node); - return ts.factory.updateHeritageClause(node, visitList(node.types, ts.isExpressionWithTypeArguments)); - case 288 /* CatchClause */: - ts.Debug.type(node); - return ts.factory.updateCatchClause(node, visit(node.variableDeclaration, ts.isVariableDeclaration), visit(node.block, ts.isBlock)); - // Property assignments - case 289 /* PropertyAssignment */: - ts.Debug.type(node); - return ts.factory.updatePropertyAssignment(node, visitPropertyName(node.name), visitExpression(node.initializer)); - case 290 /* ShorthandPropertyAssignment */: - ts.Debug.type(node); - return ts.factory.updateShorthandPropertyAssignment(node, visitIdentifierName(node.name, ts.isIdentifier), visitExpression(node.objectAssignmentInitializer)); - case 291 /* SpreadAssignment */: - ts.Debug.type(node); - return ts.factory.updateSpreadAssignment(node, visitExpression(node.expression)); - // Enum - case 292 /* EnumMember */: - ts.Debug.type(node); - return ts.factory.updateEnumMember(node, visitPropertyName(node.name), visitExpression(node.initializer)); - // JSDoc nodes (only used in codefixes currently) - case 302 /* JSDocTypeExpression */: - case 303 /* JSDocNameReference */: - case 304 /* JSDocAllType */: - case 305 /* JSDocUnknownType */: - case 306 /* JSDocNullableType */: - case 307 /* JSDocNonNullableType */: - case 308 /* JSDocOptionalType */: - case 309 /* JSDocFunctionType */: - case 310 /* JSDocVariadicType */: - case 311 /* JSDocNamepathType */: - case 312 /* JSDocComment */: - case 314 /* JSDocTypeLiteral */: - case 315 /* JSDocSignature */: - case 317 /* JSDocTag */: - case 318 /* JSDocAugmentsTag */: - case 319 /* JSDocImplementsTag */: - case 320 /* JSDocAuthorTag */: - case 321 /* JSDocDeprecatedTag */: - case 322 /* JSDocClassTag */: - case 323 /* JSDocPublicTag */: - case 324 /* JSDocPrivateTag */: - case 325 /* JSDocProtectedTag */: - case 326 /* JSDocReadonlyTag */: - case 328 /* JSDocCallbackTag */: - case 329 /* JSDocEnumTag */: - case 330 /* JSDocParameterTag */: - case 337 /* JSDocPropertyTag */: - case 331 /* JSDocReturnTag */: - case 332 /* JSDocThisTag */: - case 333 /* JSDocTypeTag */: - case 334 /* JSDocTemplateTag */: - case 335 /* JSDocTypedefTag */: - case 336 /* JSDocSeeTag */: - return node; - // Transformation nodes (ignored) - } - if (ts.isExpression(node)) { - // If this was an expression that was originally in an `Unspecified` hint, - // re-trigger substitution using the correct hint. - hint = 1 /* Expression */; - if (substituteNode !== ts.noEmitSubstitution) { - node = substituteNode(hint, node); - } - } - else if (ts.isSourceFile(node)) { - return preprintSourceFile(node); - } - } - if (hint === 1 /* Expression */) { - switch (node.kind) { - // Identifiers - case 78 /* Identifier */: - return preprintIdentifier(node); - // Expression - case 200 /* ArrayLiteralExpression */: - ts.Debug.type(node); - return ts.factory.updateArrayLiteralExpression(node, visitExpressionList(node.elements)); - case 201 /* ObjectLiteralExpression */: - ts.Debug.type(node); - return ts.factory.updateObjectLiteralExpression(node, visitList(node.properties, ts.isObjectLiteralElementLike)); - case 202 /* PropertyAccessExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updatePropertyAccessChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitMemberName(node.name)); - } - ts.Debug.type(node); - return ts.factory.updatePropertyAccessExpression(node, visitExpression(node.expression), visitMemberName(node.name)); - case 203 /* ElementAccessExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateElementAccessChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitExpression(node.argumentExpression)); - } - ts.Debug.type(node); - return ts.factory.updateElementAccessExpression(node, visitExpression(node.expression), visitExpression(node.argumentExpression)); - case 204 /* CallExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateCallChain(node, visitExpression(node.expression), visit(node.questionDotToken, ts.isQuestionDotToken), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - } - ts.Debug.type(node); - return ts.factory.updateCallExpression(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - case 205 /* NewExpression */: - ts.Debug.type(node); - return ts.factory.updateNewExpression(node, visitExpression(node.expression), visitTypeNodeList(node.typeArguments), visitExpressionList(node.arguments)); - case 206 /* TaggedTemplateExpression */: - ts.Debug.type(node); - return ts.factory.updateTaggedTemplateExpression(node, visitExpression(node.tag), visitTypeNodeList(node.typeArguments), visitExpression(node.template, ts.isTemplateLiteral)); - case 207 /* TypeAssertionExpression */: - ts.Debug.type(node); - return ts.factory.updateTypeAssertion(node, visitTypeNode(node.type), visitExpression(node.expression)); - case 208 /* ParenthesizedExpression */: - ts.Debug.type(node); - return ts.factory.updateParenthesizedExpression(node, visitExpression(node.expression)); - case 209 /* FunctionExpression */: - ts.Debug.type(node); - return ts.factory.updateFunctionExpression(node, visitList(node.modifiers, ts.isModifier), visit(node.asteriskToken, ts.isAsteriskToken), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visitFunctionBody(node.body)); - case 210 /* ArrowFunction */: - ts.Debug.type(node); - return ts.factory.updateArrowFunction(node, visitList(node.modifiers, ts.isModifier), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitParameterList(node.parameters), visitTypeNode(node.type), visit(node.equalsGreaterThanToken, ts.isEqualsGreaterThanToken), visitConciseBody(node.body)); - case 211 /* DeleteExpression */: - ts.Debug.type(node); - return ts.factory.updateDeleteExpression(node, visitExpression(node.expression)); - case 212 /* TypeOfExpression */: - ts.Debug.type(node); - return ts.factory.updateTypeOfExpression(node, visitExpression(node.expression)); - case 213 /* VoidExpression */: - ts.Debug.type(node); - return ts.factory.updateVoidExpression(node, visitExpression(node.expression)); - case 214 /* AwaitExpression */: - ts.Debug.type(node); - return ts.factory.updateAwaitExpression(node, visitExpression(node.expression)); - case 215 /* PrefixUnaryExpression */: - ts.Debug.type(node); - return ts.factory.updatePrefixUnaryExpression(node, visitExpression(node.operand)); - case 216 /* PostfixUnaryExpression */: - ts.Debug.type(node); - return ts.factory.updatePostfixUnaryExpression(node, visitExpression(node.operand)); - case 217 /* BinaryExpression */: - return preprintBinaryExpression(node); - case 218 /* ConditionalExpression */: - ts.Debug.type(node); - return ts.factory.updateConditionalExpression(node, visitExpression(node.condition), visit(node.questionToken, ts.isQuestionToken), visitExpression(node.whenTrue), visit(node.colonToken, ts.isColonToken), visitExpression(node.whenFalse)); - case 219 /* TemplateExpression */: - ts.Debug.type(node); - return ts.factory.updateTemplateExpression(node, visit(node.head, ts.isTemplateHead), visitList(node.templateSpans, ts.isTemplateSpan)); - case 220 /* YieldExpression */: - ts.Debug.type(node); - return ts.factory.updateYieldExpression(node, visit(node.asteriskToken, ts.isAsteriskToken), visitExpression(node.expression)); - case 221 /* SpreadElement */: - ts.Debug.type(node); - return ts.factory.updateSpreadElement(node, visitExpression(node.expression)); - case 222 /* ClassExpression */: - ts.Debug.type(node); - return ts.factory.updateClassExpression(node, visitList(node.decorators, ts.isDecorator), visitList(node.modifiers, ts.isModifier), visitIdentifierName(node.name), visitList(node.typeParameters, ts.isTypeParameterDeclaration), visitList(node.heritageClauses, ts.isHeritageClause), visitList(node.members, ts.isClassElement)); - case 225 /* AsExpression */: - ts.Debug.type(node); - return ts.factory.updateAsExpression(node, visitExpression(node.expression), visitTypeNode(node.type)); - case 226 /* NonNullExpression */: - if (node.flags & 32 /* OptionalChain */) { - ts.Debug.type(node); - return ts.factory.updateNonNullChain(node, visitExpression(node.expression)); - } - ts.Debug.type(node); - return ts.factory.updateNonNullExpression(node, visitExpression(node.expression)); - case 227 /* MetaProperty */: - ts.Debug.type(node); - return ts.factory.updateMetaProperty(node, visitIdentifierName(node.name)); - // JSX (expression only) - case 274 /* JsxElement */: - ts.Debug.type(node); - return ts.factory.updateJsxElement(node, visit(node.openingElement, ts.isJsxOpeningElement), visitList(node.children, ts.isJsxChild), visit(node.closingElement, ts.isJsxClosingElement)); - case 275 /* JsxSelfClosingElement */: - ts.Debug.type(node); - return ts.factory.updateJsxSelfClosingElement(node, visitExpression(node.tagName, ts.isJsxTagNameExpression), visitList(node.typeArguments, ts.isTypeNode), visit(node.attributes, ts.isJsxAttributes)); - case 278 /* JsxFragment */: - ts.Debug.type(node); - return ts.factory.updateJsxFragment(node, visit(node.openingFragment, ts.isJsxOpeningFragment), visitList(node.children, ts.isJsxChild), visit(node.closingFragment, ts.isJsxClosingFragment)); - // Transformation nodes - case 340 /* PartiallyEmittedExpression */: - ts.Debug.type(node); - return ts.factory.updatePartiallyEmittedExpression(node, visitExpression(node.expression)); - case 341 /* CommaListExpression */: - ts.Debug.type(node); - return ts.factory.updateCommaListExpression(node, visitExpressionList(node.elements, ts.isExpression)); - } - } - if (ts.Debug.shouldAssert(1 /* Normal */)) { - // Any other node should not have children or this list isn't up to date. - ts.Debug.assertMissingNode(ts.forEachChild(node, ts.identity), "Expected " + ts.Debug.formatSyntaxKind(node.kind) + " to contain no children."); - } - // No need to visit nodes with no children. - return node; - } - function preprintSourceFile(node) { - return ts.factory.updateSourceFile(node, visitList(node.statements, ts.isStatement)); - } - function preprintIdentifier(node) { - return ts.factory.updateIdentifier(node, visitList(node.typeArguments, ts.isTypeNodeOrTypeParameterDeclaration)); - } - function preprintTypeParameterDeclaration(node) { - return ts.factory.updateTypeParameterDeclaration(node, visitIdentifierName(node.name), visitTypeNode(node.constraint), visitTypeNode(node.default)); - } - function createPreprintBinaryExpression() { - return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); - function onEnter(node, state) { - if (state) { - state.stackIndex++; - state.leftStack[state.stackIndex] = node.left; - state.operatorStack[state.stackIndex] = node.operatorToken; - state.rightStack[state.stackIndex] = node.right; - } - else { - state = { - stackIndex: 0, - leftStack: [node.left], - operatorStack: [node.operatorToken], - rightStack: [node.right], - }; - } - return state; - } - function onLeft(left, state, _node) { - return maybeVisitExpression(left, state, "left"); - } - function onOperator(operator, state, _node) { - state.operatorStack[state.stackIndex] = visit(operator, ts.isBinaryOperatorToken); - } - function onRight(right, state, _node) { - return maybeVisitExpression(right, state, "right"); - } - function onExit(node, state) { - var left = state.leftStack[state.stackIndex]; - var operator = state.operatorStack[state.stackIndex]; - var right = state.rightStack[state.stackIndex]; - if (state.stackIndex > 0) { - state.stackIndex--; - } - return ts.factory.updateBinaryExpression(node, left, operator, right); - } - function foldState(state, result, side) { - (side === "left" ? state.leftStack : state.rightStack)[state.stackIndex] = result; - return state; - } - function maybeVisitExpression(node, state, side) { - // Get the first supported pipeline phase for this node. We can skip several stack - // frames if we aren't doing emit notification, so we check for substitution and - // direct callbacks and execute those immediately. - var pipelinePhase = getPipelinePhase(0 /* Notification */, node); - if (pipelinePhase === pipelineVisitWithSubstitution) { - // The next phase after substitution is always direct visitation, so we can reduce the call stack - // depth by proceding to the direct visitor. - node = ts.cast(substituteNode(1 /* Expression */, node), ts.isExpression); - pipelinePhase = pipelineVisitDirect; - } - if (pipelinePhase === pipelineVisitDirect && ts.isBinaryExpression(node)) { - // If we are visiting directly and the next node is a BinaryExpression, we can - // add it to the stack and continue the trampoline. - return node; - } - else { - // Visit the expression and store the result on whichever side we are currently visiting. - (side === "left" ? state.leftStack : state.rightStack)[state.stackIndex] = visitExpression(node, ts.isExpression); - } - } - } - var preprintBinaryExpression = createPreprintBinaryExpression(); - function preprint(hint, node) { - // If we're not performing substitution or notification, we have no work to do here. - if (substituteNode === ts.noEmitSubstitution && - onEmitNode === ts.noEmitNotification) { - return node; - } - switch (hint) { - case 0 /* SourceFile */: return visitSourceFile(ts.cast(node, ts.isSourceFile)); - case 1 /* Expression */: return visitExpression(ts.cast(node, ts.isExpression)); - case 2 /* IdentifierName */: return visitIdentifierName(ts.cast(node, ts.isIdentifier)); - case 3 /* MappedTypeParameter */: return visitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 5 /* EmbeddedStatement */: return visitEmbeddedStatement(ts.cast(node, ts.isStatement)); - case 6 /* JsxAttributeValue */: return visitJsxAttributeValue(ts.cast(node, ts.isStringLiteralOrJsxExpression)); - default: return visit(node); - } - } - return preprint; - } function createBracketsMap() { var brackets = []; brackets[1024 /* Braces */] = ["{", "}"]; @@ -109229,6 +109165,7 @@ var ts; var hasEmitBlockingDiagnostics = new ts.Map(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; + var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { @@ -109243,7 +109180,7 @@ var ts; }); }; } else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } @@ -109252,7 +109189,8 @@ var ts; actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { - var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; // TODO: GH#18217 actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -109409,6 +109347,7 @@ var ts; } }); } + typeReferenceDirectiveResolutionCache = undefined; // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; var program = { @@ -109602,13 +109541,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_15 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_14.push(resolvedModule); + result_15.push(resolvedModule); } - return result_14; + return result_15; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -111040,12 +110979,14 @@ var ts; return host.getCanonicalFileName(fileName); } function processImportedModules(file) { + var _a; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var resolutions = resolveModuleNamesReusingOldState(moduleNames, file); ts.Debug.assert(resolutions.length === moduleNames.length); + var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options; for (var index = 0; index < moduleNames.length; index++) { var resolution = resolutions[index]; ts.setResolvedModule(file, moduleNames[index], resolution); @@ -111068,11 +111009,11 @@ var ts; // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !ts.getAllowJSCompilerOption(options)) + && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile)) && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -112160,7 +112101,7 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos: fileInfos, @@ -112960,7 +112901,16 @@ var ts; var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - return signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; + var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); var referencedMap; if (state.referencedMap) { @@ -113009,7 +112959,7 @@ var ts; return { fileNames: fileNames, fileInfos: fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, @@ -113041,17 +112991,16 @@ var ts; return fileIdListId; } } - function convertToReusableCompilerOptions(options, relativeToBuildInfo) { - var result = {}; + function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { + var result; var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo); + 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.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { @@ -113367,6 +113316,14 @@ var ts; state.affectedFilesPendingEmitIndex = 0; } } + function toBuilderStateFileInfo(fileInfo) { + return ts.isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + ts.isString(fileInfo.signature) ? + fileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; + } + ts.toBuilderStateFileInfo = toBuilderStateFileInfo; function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { var _a; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); @@ -113374,10 +113331,10 @@ var ts; 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), fileInfo); }); + program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); var state = { fileInfos: fileInfos, - compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, referencedMap: toMapOfReferencedSet(program.referencedMap), exportedModulesMap: toMapOfReferencedSet(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]; }), @@ -113537,9 +113494,9 @@ var ts; var resolutionsWithFailedLookups = []; var resolvedFileToResolution = ts.createMultiMap(); var hasChangedAutomaticTypeDirectiveNames = false; - var failedLookupChecks = []; - var startsWithPathChecks = []; - var isInDirectoryChecks = []; + var failedLookupChecks; + var startsWithPathChecks; + var isInDirectoryChecks; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -113548,9 +113505,12 @@ var ts; var resolvedModuleNames = new ts.Map(); var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache); var resolvedTypeReferenceDirectives = new ts.Map(); var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -113608,9 +113568,9 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.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(); @@ -113646,9 +113606,8 @@ var ts; isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -113675,7 +113634,7 @@ 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), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; @@ -113686,6 +113645,9 @@ var ts; // Default return the result from the first pass return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } function resolveNamesWithLocalCache(_a) { var _b; var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; @@ -113773,7 +113735,7 @@ var ts; redirectedReference: redirectedReference, cache: resolvedTypeReferenceDirectives, perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, - loader: ts.resolveTypeReferenceDirective, + loader: resolveTypeReferenceDirective, getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, }); @@ -114048,7 +114010,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -114066,8 +114028,8 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -114078,27 +114040,33 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(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. + var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { return resolution.failedLookupLocations.some(function (location) { var locationPath = resolutionHost.toPath(location); return ts.contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) || - isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, 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); })); }); } function closeTypeRootsWatch() { @@ -114319,7 +114287,7 @@ var ts; if (!baseUrl && !paths || relativePreference === 0 /* Relative */) { return relativePath; } - var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl; + var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -114334,7 +114302,9 @@ var ts; return nonRelative; } if (relativePreference === 3 /* ExternalNonRelative */) { - var projectDirectory = host.getCurrentDirectory(); + var projectDirectory = compilerOptions.configFilePath ? + ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName); var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory); var targetIsInternal = ts.startsWith(modulePath, projectDirectory); @@ -114409,9 +114379,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 links = host.getSymlinkCache ? host.getSymlinkCache() @@ -114434,10 +114404,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; } }); }); @@ -114568,7 +114538,7 @@ var ts; ts.startsWith(relativeToBaseUrl, prefix) && ts.endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } @@ -116169,12 +116139,19 @@ var ts; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); 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) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } + if (!compilerHost.resolveTypeReferenceDirectives) { + var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4); + }; + } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -116199,6 +116176,7 @@ var ts; projectErrorsReported: new ts.Map(), compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, + typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, // Mutable state buildOrder: undefined, readFileWithCache: function (f) { return host.readFile(f); }, @@ -116386,7 +116364,7 @@ var ts; function disableCache(state) { if (!state.cache) return; - var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache; + var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -116395,10 +116373,8 @@ var ts; compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear(); state.cache = undefined; } function clearProjectStatus(state, resolved) { @@ -116565,6 +116541,7 @@ var ts; return withProgramOrUndefined(action) || ts.emptyArray; } function createProgram() { + var _a, _b; ts.Debug.assert(program === undefined); if (state.options.dry) { reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -116584,7 +116561,8 @@ var ts; var host = state.host, compilerHost = state.compilerHost; state.projectCompilerOptions = config.options; // Update module resolution cache if needed - updateModuleResolutionCache(state, project, config); + (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { @@ -116759,7 +116737,7 @@ var ts; emitBundle(writeFile, customTransformers); break; case BuildStep.BuildInvalidatedProjectOfBundle: - ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; case BuildStep.QueueReferencingProjects: @@ -116901,31 +116879,6 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache(state, proj, config) { - if (!state.moduleResolutionCache) - return; - // Update module resolution cache if needed - var moduleResolutionCache = state.moduleResolutionCache; - var projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - // The own map will be for projectCompilerOptions - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - // Set correct own map - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - var ref = { - sourceFile: config.options.configFile, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time var tsconfigTime = ts.getModifiedTime(state.host, configFile); @@ -116938,6 +116891,7 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { + var force = !!state.options.force; var newestInputFileName = undefined; var newestInputFileTime = minimumDate; var host = state.host; @@ -116950,11 +116904,13 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = ts.getModifiedTime(host, inputFile); - host.getModifiedTime(inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + var inputTime = ts.getModifiedTime(host, inputFile); + host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } // Container if no files are specified in the project @@ -116973,36 +116929,38 @@ var ts; var missingOutputFileName; var newestDeclarationFileContentChangedTime = minimumDate; var isOutOfDateWithInputs = false; - 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 (isDeclarationFile(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + 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 (isDeclarationFile(output)) { + var outputModifiedTime = ts.getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } var pseudoUpToDate = false; @@ -117038,7 +116996,8 @@ var ts; }; } // Check oldest output file name only if there is no missing output file name - if (!missingOutputFileName) { + // (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) { @@ -117084,7 +117043,7 @@ var ts; if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -117226,7 +117185,7 @@ var ts; } } } - function build(state, project, cancellationToken, onlyReferences) { + function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -117238,7 +117197,7 @@ var ts; if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -117420,9 +117379,9 @@ var ts; function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: function (project, cancellationToken) { return build(state, project, cancellationToken); }, + build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); }, clean: function (project) { return clean(state, project); }, - buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); }, + buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, /*onlyReferences*/ true); }, cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); }, getNextInvalidatedProject: function (cancellationToken) { setupInitialBuild(state, cancellationToken); @@ -117512,6 +117471,9 @@ 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)); diff --git a/package.json b/package.json index 92a33852d31ae..c5270a50a2e24 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "https://www.typescriptlang.org/", - "version": "4.3.0-beta", + "version": "4.3.1-rc", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ diff --git a/src/compiler/corePublic.ts b/src/compiler/corePublic.ts index 0c34b4d3314c1..f0fb790244b1c 100644 --- a/src/compiler/corePublic.ts +++ b/src/compiler/corePublic.ts @@ -5,7 +5,7 @@ namespace ts { // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - export const version = `${versionMajorMinor}.0-beta`; + export const version = "4.3.1-rc" as string; /** * Type of objects whose values are all of the same type.