From 48fa3a5f18a7090a7b3fb8836159fee7e48a8013 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Fri, 15 Nov 2019 10:31:30 -0800 Subject: [PATCH] Update LKG (#35128) --- lib/cs/diagnosticMessages.generated.json | 2 +- lib/de/diagnosticMessages.generated.json | 2 +- lib/es/diagnosticMessages.generated.json | 4 +- lib/fr/diagnosticMessages.generated.json | 6 +- lib/ja/diagnosticMessages.generated.json | 30 +- lib/lib.dom.d.ts | 4 +- lib/lib.es5.d.ts | 16 +- lib/lib.webworker.d.ts | 4 +- lib/pl/diagnosticMessages.generated.json | 8 +- lib/protocol.d.ts | 12 +- lib/ru/diagnosticMessages.generated.json | 30 +- lib/tr/diagnosticMessages.generated.json | 2 +- lib/tsc.js | 3360 +++++++++------- lib/tsserver.js | 3981 +++++++++++-------- lib/tsserverlibrary.d.ts | 35 +- lib/tsserverlibrary.js | 3940 ++++++++++-------- lib/typescript.d.ts | 13 +- lib/typescript.js | 3757 +++++++++-------- lib/typescriptServices.d.ts | 13 +- lib/typescriptServices.js | 3757 +++++++++-------- lib/typingsInstaller.js | 3551 +++++++++-------- lib/zh-cn/diagnosticMessages.generated.json | 4 +- 22 files changed, 12767 insertions(+), 9764 deletions(-) diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json index 32a067f4fe8..fabd59da8cd 100644 --- a/lib/cs/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -441,7 +441,7 @@ "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Implementace funkce chybí nebo nenásleduje hned po deklaraci.", "Function_implementation_name_must_be_0_2389": "Název implementace funkce musí být {0}.", "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Funkce implicitně obsahuje návratový typ any, protože neobsahuje anotaci návratového typu a odkazuje se na ni přímo nebo nepřímo v jednom z jejích návratových výrazů.", - "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Ve funkci chybí koncový návratový příkaz a návratový typ neobsahuje undefined.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Ve funkci chybí koncový příkaz return a návratový typ neobsahuje undefined.", "Function_overload_must_be_static_2387": "Přetížení funkce musí být statické.", "Function_overload_must_not_be_static_2388": "Přetížení funkce nesmí být statické.", "Generate_get_and_set_accessors_95046": "Generovat přístupové objekty get a set", diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index f7bf53b6755..d010e950339 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -1032,7 +1032,7 @@ "await_expression_is_only_allowed_within_an_async_function_1308": "Der Ausdruck \"await\" ist nur in einer asynchronen Funktion zulässig.", "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "await-Ausdrücke dürfen nicht in einem Parameterinitialisierer verwendet werden.", "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "Die Option \"baseUrl\" ist auf \"{0}\" festgelegt. Dieser Wert wird verwendet, um den nicht relativen Modulnamen \"{1}\" aufzulösen.", - "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" kann nur in einer Objektliteraleigenschaft innerhalb eines Destrukturierungsauftrags verwendet werden.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" kann nur in einer Objektliteraleigenschaft innerhalb eines Destrukturierungszuweisung verwendet werden.", "case_or_default_expected_1130": "\"case\" oder \"default\" wurde erwartet.", "class_expressions_are_not_currently_supported_9003": "class-Ausdrücke werden zurzeit nicht unterstützt.", "const_declarations_can_only_be_declared_inside_a_block_1156": "const-Deklarationen können nur innerhalb eines Blocks deklariert werden.", diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 52840b1208e..c0ce6ef5b8d 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -441,7 +441,7 @@ "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Falta la implementación de función o no sigue inmediatamente a la declaración.", "Function_implementation_name_must_be_0_2389": "El nombre de la implementación de función debe ser '{0}'.", "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "La función tiene el tipo de valor devuelto \"any\" implícitamente porque no tiene una anotación de tipo de valor devuelto y se hace referencia a ella directa o indirectamente en una de sus expresiones return.", - "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Falta la instrucción return final en la función y el tipo de valor devuelto no incluye 'undefined'.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Falta la instrucción \"return\" final en la función y el tipo de valor devuelto no incluye 'undefined'.", "Function_overload_must_be_static_2387": "La sobrecarga de función debe ser estática.", "Function_overload_must_not_be_static_2388": "La sobrecarga de función no debe ser estática.", "Generate_get_and_set_accessors_95046": "Generar los descriptores de acceso \"get\" y \"set\"", @@ -453,7 +453,7 @@ "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Los generadores solo están disponibles cuando el destino es ECMAScript 2015 o una versión posterior.", "Generic_type_0_requires_1_type_argument_s_2314": "El tipo genérico '{0}' requiere los siguientes argumentos de tipo: {1}.", "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "El tipo genérico \"{0}\" requiere entre {1} y {2} argumentos de tipo.", - "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "La creación de instancias de tipo genérico es excesivamente profunda y posiblemente infinita.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "La creación de una instancia de tipo genérico es excesivamente profunda y posiblemente infinita.", "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Los descriptores de acceso de captador y establecedor no se corresponden respecto a la visibilidad.", "Global_module_exports_may_only_appear_at_top_level_1316": "Las exportaciones de módulos globales solo pueden aparecer en el nivel superior.", "Global_module_exports_may_only_appear_in_declaration_files_1315": "Las exportaciones de módulos globales solo pueden aparecer en archivos de declaración.", diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json index 1699b44df8b..7a84aae4982 100644 --- a/lib/fr/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -142,7 +142,7 @@ "An_async_iterator_must_have_a_next_method_2519": "Un itérateur asynchrone doit comporter une méthode 'next()'.", "An_element_access_expression_should_take_an_argument_1011": "Une expression d'accès à un élément doit accepter un argument.", "An_enum_member_cannot_have_a_numeric_name_2452": "Un membre enum ne peut pas avoir un nom numérique.", - "An_export_assignment_can_only_be_used_in_a_module_1231": "Une attribution d'exportation peut uniquement être utilisée dans un module.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Une affectation d'exportation peut uniquement être utilisée dans un module.", "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Impossible d'utiliser une assignation d'exportation dans un module comportant d'autres éléments exportés.", "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Une affectation d'exportation ne peut pas être utilisée dans un espace de noms.", "An_export_assignment_cannot_have_modifiers_1120": "Une assignation d'exportation ne peut pas avoir de modificateurs.", @@ -594,7 +594,7 @@ "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Aucune entrée dans le fichier config '{0}'. Les chemins 'include' spécifiés étaient '{1}' et les chemins 'exclude' étaient '{2}'.", "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "La classe non abstraite '{0}' n'implémente pas le membre abstrait '{1}' hérité de la classe '{2}'.", "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "L'expression de classe non abstraite '{0}' n'implémente pas le membre abstrait hérité '{0}' de la classe '{1}'.", - "Not_all_code_paths_return_a_value_7030": "Les chemins de code ne retournent pas tous une valeur.", + "Not_all_code_paths_return_a_value_7030": "Les chemins du code ne retournent pas tous une valeur.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Impossible d'assigner le type d'index numérique '{0}' au type d'index de chaîne '{1}'.", "Numeric_separators_are_not_allowed_here_6188": "Les séparateurs numériques ne sont pas autorisés ici.", "Object_is_of_type_unknown_2571": "L'objet est de type 'unknown'.", @@ -745,7 +745,7 @@ "Remove_unused_label_95053": "Supprimer l'étiquette inutilisée", "Remove_variable_statement_90010": "Supprimer l'instruction de variable", "Replace_import_with_0_95015": "Remplacez l'importation par '{0}'.", - "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins de code de la fonction ne retournent pas tous une valeur.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins du code de la fonction ne retournent pas tous une valeur.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Signalez les erreurs pour les case avec fallthrough dans une instruction switch.", "Report_errors_in_js_files_8019": "Signalez les erreurs dans les fichiers .js.", "Report_errors_on_unused_locals_6134": "Signaler les erreurs sur les variables locales inutilisées.", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index d3029982ca6..751357dbc01 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -130,7 +130,7 @@ "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' フラグが指定されている場合、アンビエント const 列挙型は使用できません。", "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "アンビエント モジュール宣言では、相対モジュール名を指定できません。", "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "アンビエント モジュールを、他のモジュールまたは名前空間内の入れ子にすることはできません。", - "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD モジュールに複数の名前を割り当てることはできません。", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD モジュールに複数の名前を代入することはできません。", "An_abstract_accessor_cannot_have_an_implementation_1318": "抽象アクセサーに実装を含めることはできません。", "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "環境コンテキストではアクセサーは宣言できません。", "An_accessor_cannot_have_type_parameters_1094": "アクセサーに型パラメーターを指定することはできません。", @@ -142,10 +142,10 @@ "An_async_iterator_must_have_a_next_method_2519": "非同期反復子には 'next()' メソッドが必要です。", "An_element_access_expression_should_take_an_argument_1011": "要素アクセス式では、引数を取る必要があります。", "An_enum_member_cannot_have_a_numeric_name_2452": "列挙型メンバーに数値名を含めることはできません。", - "An_export_assignment_can_only_be_used_in_a_module_1231": "エクスポートの割り当てはモジュールでのみ使用可能です。", - "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの割り当ては、エクスポートされた他の要素を含むモジュールでは使用できません。", - "An_export_assignment_cannot_be_used_in_a_namespace_1063": "エクスポートの割り当ては、名前空間では使用できません。", - "An_export_assignment_cannot_have_modifiers_1120": "エクスポートの割り当てに修飾子を指定することはできません。", + "An_export_assignment_can_only_be_used_in_a_module_1231": "エクスポートの代入はモジュールでのみ使用可能です。", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの代入は、エクスポートされた他の要素を含むモジュールでは使用できません。", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "エクスポートの代入は、名前空間では使用できません。", + "An_export_assignment_cannot_have_modifiers_1120": "エクスポートの代入に修飾子を指定することはできません。", "An_export_declaration_can_only_be_used_in_a_module_1233": "エクスポート宣言はモジュールでのみ使用可能です。", "An_export_declaration_cannot_have_modifiers_1193": "エクスポート宣言に修飾子を指定することはできません。", "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "拡張された Unicode エスケープ値は 0x0 と 0x10FFFF の間 (両端を含む) でなければなりません。", @@ -389,8 +389,8 @@ "Experimental_Options_6177": "試験的なオプション", "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "デコレーターの実験的なサポートは将来のリリースで変更になる可能性がある機能です。'experimentalDecorators' オプションを設定してこの警告を削除します。", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "明示的に指定されたモジュール解決の種類 '{0}'。", - "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript モジュールを対象にする場合は、エクスポート割り当てを使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。", - "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "割り当てのエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript モジュールを対象にする場合は、エクスポート代入を使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "代入のエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "エクスポート宣言が、'{0}' のエクスポートされた宣言と競合しています。", "Export_declarations_are_not_permitted_in_a_namespace_1194": "エクスポート宣言は名前空間でサポートされません。", "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "エクスポートされた外部パッケージの型指定のファイル '{0}' はモジュールではありません。パッケージ定義を更新する場合は、パッケージの作成者にお問い合わせください。", @@ -399,7 +399,7 @@ "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "エクスポートされた変数 '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "エクスポートされた変数 '{0}' がプライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", "Exported_variable_0_has_or_is_using_private_name_1_4025": "エクスポートされた変数 '{0}' がプライベート名 '{1}' を持っているか、使用しています。", - "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "エクスポートとエクスポートの割り当てはモジュールの拡張では許可されていません。", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "エクスポートとエクスポートの代入はモジュールの拡張では許可されていません。", "Expression_expected_1109": "式が必要です。", "Expression_or_comma_expected_1137": "式またはコンマが必要です。", "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "式は、コンパイラが基底クラスの参照をキャプチャするために使用する '_super' に解決されます。", @@ -473,7 +473,7 @@ "Implement_interface_0_90006": "インターフェイス '{0}' を実装する", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "エクスポートされたクラス '{0}' の Implements 句がプライベート名 '{1}' を持っているか、使用しています。", "Import_0_from_module_1_90013": "モジュール \"{1}\" から '{0}' をインポートする", - "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript モジュールを対象にする場合は、インポート割り当てを使用できません。代わりに 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' などのモジュール書式の使用をご検討ください。", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript モジュールを対象にする場合は、インポート代入を使用できません。代わりに 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' などのモジュール書式の使用をご検討ください。", "Import_declaration_0_is_using_private_name_1_4000": "インポート宣言 '{0}' がプライベート名 '{1}' を使用しています。", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "インポート宣言が、'{0}' のローカル宣言と競合しています。", "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "名前空間内のインポート宣言は、モジュールを参照できません。", @@ -536,7 +536,7 @@ "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 要素に同じ名前の複数の属性を指定することはできません。", "JSX_expressions_must_have_one_parent_element_2657": "JSX 式には 1 つの親要素が必要です。", "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX フラグメントには対応する終了タグがありません。", - "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "JSX フラグメントはインライン JSX ファクトリ プラグマの使用時にサポートされていません", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "JSX フラグメントはインライン JSX ファクトリ pragma の使用時にサポートされていません", "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "--jsxFactory を使う場合、JSX フラグメントはサポートされません", "JSX_spread_child_must_be_an_array_type_2609": "JSX スプレッドの子は、配列型でなければなりません。", "Jump_target_cannot_cross_function_boundary_1107": "ジャンプ先は関数の境界を越えることはできません。", @@ -714,7 +714,7 @@ "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "型 '{1}' のプロパティ '{0}' を数値インデックス型 '{2}' に割り当てることはできません。", "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "型 '{1}' のプロパティ '{0}' を文字列インデックス型 '{2}' に割り当てることはできません。", - "Property_assignment_expected_1136": "プロパティの割り当てが必要です。", + "Property_assignment_expected_1136": "プロパティの代入が必要です。", "Property_destructuring_pattern_expected_1180": "プロパティの非構造化パターンが必要です。", "Property_or_signature_expected_1131": "プロパティまたはシグネチャが必要です。", "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "プロパティ値には、文字列リテラル、数値リテラル、'true'、'false'、'null'、オブジェクト リテラルまたは配列リテラルのみ使用できます。", @@ -850,7 +850,7 @@ "The_character_set_of_the_input_files_6163": "入力ファイルの文字セット。", "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "含まれている関数またはモジュールの本体は、制御フロー解析には大きすぎます。", "The_current_host_does_not_support_the_0_option_5001": "現在のホストは '{0}' オプションをサポートしていません。", - "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "エクスポートの割り当ての式は、環境コンテキストの識別子または修飾名にする必要があります。", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "エクスポートの代入の式は、環境コンテキストの識別子または修飾名にする必要があります。", "The_files_list_in_config_file_0_is_empty_18002": "構成ファイル '{0}' の 'files' リストが空です。", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise では、'then' メソッドの最初のパラメーターはコールバックでなければなりません。", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "グローバル型 'JSX.{0}' には複数のプロパティが含まれていない可能性があります。", @@ -882,7 +882,7 @@ "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "instanceof' 式の右辺には、'any' 型、または 'Function' インターフェイス型に割り当てることができる型を指定してください。", "The_specified_path_does_not_exist_Colon_0_5058": "指定されたパスがありません: '{0}'。", "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "代入式のターゲットは、変数またはプロパティ アクセスである必要があります。", - "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "オブジェクトの残り部分の割り当ての対象は、変数またはプロパティ アクセスである必要があります。", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "オブジェクトの残り部分の代入の対象は、変数またはプロパティ アクセスである必要があります。", "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "型 '{0}' の 'this' コンテキストを型 '{1}' のメソッドの 'this' に割り当てることはできません。", "The_this_types_of_each_signature_are_incompatible_2685": "各シグネチャの 'this' 型に互換性がありません。", "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "型パラメーター '{0}' の型引数を使用法から推論することはできません。型引数を明示的に指定してください。", @@ -1032,14 +1032,14 @@ "await_expression_is_only_allowed_within_an_async_function_1308": "'await' 式は、非同期関数内でのみ使用できます。", "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' 式は、パラメーター初期化子では使用できません。", "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' オプションは '{0}' に設定され、この値を使用して非相対モジュール名 '{1}' を解決します。", - "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' は、非構造化割り当て内のオブジェクト リテラル プロパティでのみ使用できます。", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' は、非構造化代入内のオブジェクト リテラル プロパティでのみ使用できます。", "case_or_default_expected_1130": "'case' または 'default' が必要です。", "class_expressions_are_not_currently_supported_9003": "'class' 式は現在サポートされていません。", "const_declarations_can_only_be_declared_inside_a_block_1156": "'const' 宣言は、ブロック内でのみ宣言できます。", "const_declarations_must_be_initialized_1155": "'const' 宣言は初期化する必要があります。", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 列挙型メンバーの初期化子が、無限値に評価されました。", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 列挙型メンバーの初期化子が、許可されない値 'NaN' に評価されました。", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列挙型は、プロパティまたはインデックスのアクセス式、インポート宣言またはエクスポートの割り当ての右辺、型のクエリにのみ使用できます。", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列挙型は、プロパティまたはインデックスのアクセス式、インポート宣言またはエクスポートの代入の右辺、型のクエリにのみ使用できます。", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "厳格モードでは 'delete' を識別子で呼び出すことはできません。", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "これを削除します - プロジェクト '{0}' は、以前にビルドされているため、最新の状態です", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'列挙型宣言' を使用できるのは .ts ファイル内のみです。", diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index da1ba2985dc..4217884bca4 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -9782,7 +9782,7 @@ interface ImageData { declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; - new(array: Uint8ClampedArray, width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height?: number): ImageData; }; interface InnerHTML { @@ -19103,7 +19103,7 @@ declare namespace WebAssembly { var Instance: { prototype: Instance; - new(module: Module, importObject?: any): Instance; + new(module: Module, importObject?: Imports): Instance; }; interface LinkError { diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 13bf9bb239e..a9b9f5b0aea 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -702,8 +702,8 @@ interface Math { /** Returns a pseudorandom number between 0 and 1. */ random(): number; /** - * Returns a supplied numeric expression rounded to the nearest number. - * @param x The value to be rounded to the nearest number. + * Returns a supplied numeric expression rounded to the nearest integer. + * @param x The value to be rounded to the nearest integer. */ round(x: number): number; /** @@ -893,12 +893,12 @@ interface DateConstructor { /** * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. - * @param month The month as an number between 0 and 11 (January to December). - * @param date The date as an number between 1 and 31. - * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. - * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. - * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. - * @param ms An number from 0 to 999 that specifies the milliseconds. + * @param month The month as a number between 0 and 11 (January to December). + * @param date The date as a number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds. + * @param ms A number from 0 to 999 that specifies the milliseconds. */ UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; now(): number; diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 57e9b28b531..efc1de2e994 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -2222,7 +2222,7 @@ interface ImageData { declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; - new(array: Uint8ClampedArray, width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height?: number): ImageData; }; /** This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties. */ @@ -5629,7 +5629,7 @@ declare namespace WebAssembly { var Instance: { prototype: Instance; - new(module: Module, importObject?: any): Instance; + new(module: Module, importObject?: Imports): Instance; }; interface Memory { diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index 9d219542c86..e625476e041 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -30,7 +30,7 @@ "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Dekorator może dekorować jedynie implementację metody, a nie przeciążenie.", "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Klauzula „default” nie może występować więcej niż raz w instrukcji „switch”.", "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Eksport domyślny może być używany tylko w module w stylu języka ECMAScript.", - "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Asercja określonego przydziału „!” nie jest dozwolona w tym kontekście.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Asercja określonego przypisania „!” nie jest dozwolona w tym kontekście.", "A_destructuring_declaration_must_have_an_initializer_1182": "Deklaracja usuwająca strukturę musi mieć inicjator.", "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Wywołanie dynamicznego importowania w wersji ES5/ES3 wymaga konstruktora „Promise”. Upewnij się, że masz deklarację dla konstruktora „Promise”, lub uwzględnij wartość „ES2015” w opcji „--lib”.", "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Wywołanie dynamicznego importowania zwraca element „Promise”. Upewnij się, że masz deklarację elementu „Promise” lub uwzględnij wartość „ES2015” w opcji „--lib”.", @@ -441,7 +441,7 @@ "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Brak implementacji funkcji lub nie występuje ona bezpośrednio po deklaracji.", "Function_implementation_name_must_be_0_2389": "Implementacja funkcji musi mieć nazwę „{0}”.", "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Dla funkcji niejawnie określono zwracany typ „any”, ponieważ nie zawiera ona adnotacji zwracanego typu i jest przywoływana bezpośrednio lub pośrednio w jednym z jej zwracanych wyrażeń.", - "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Funkcja nie zawiera końcowej instrukcji „return”, a zwracany typ nie obejmuje wartości „undefined”.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Funkcja nie zawiera końcowej instrukcji return, a zwracany typ nie obejmuje wartości „undefined”.", "Function_overload_must_be_static_2387": "Przeciążenie funkcji musi być statyczne.", "Function_overload_must_not_be_static_2388": "Przeciążenie funkcji nie może być statyczne.", "Generate_get_and_set_accessors_95046": "Generuj metody dostępu „get” i „set”.", @@ -594,7 +594,7 @@ "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Nie można znaleźć danych wejściowych w pliku konfiguracji „{0}”. Określone ścieżki „include” to „{1}”, a „exclude” to „{2}”.", "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Klasa nieabstrakcyjna „{0}” nie implementuje odziedziczonej abstrakcyjnej składowej „{1}” z klasy „{2}”.", "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Wyrażenie klasy nieabstrakcyjnej nie implementuje odziedziczonej abstrakcyjnej składowej „{0}” z klasy „{1}”.", - "Not_all_code_paths_return_a_value_7030": "Nie wszystkie ścieżki kodu zwracają wartość.", + "Not_all_code_paths_return_a_value_7030": "Nie wszystkie ścieżki w kodzie zwracają wartość.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Nie można przypisać typu indeksu numerycznego „{0}” do typu indeksu ciągu „{1}”.", "Numeric_separators_are_not_allowed_here_6188": "Separatory liczbowe nie są dozwolone w tym miejscu.", "Object_is_of_type_unknown_2571": "Obiekt jest typu „nieznany”.", @@ -745,7 +745,7 @@ "Remove_unused_label_95053": "Usuń nieużywaną etykietę", "Remove_variable_statement_90010": "Usuń instrukcję zmiennej", "Replace_import_with_0_95015": "Zamień import na element „{0}”.", - "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki kodu zwracają wartość.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki w kodzie zwracają wartość.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Zgłoś błędy dla przepuszczających klauzul case w instrukcji switch.", "Report_errors_in_js_files_8019": "Zgłaszaj błędy w plikach js.", "Report_errors_on_unused_locals_6134": "Raportuj błędy dla nieużywanych elementów lokalnych.", diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index def3c67bdf0..cf95f63f5ce 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -652,9 +652,11 @@ declare namespace ts.server.protocol { interface DefinitionResponse extends Response { body?: FileSpanWithContext[]; } - interface DefinitionInfoAndBoundSpanReponse extends Response { + interface DefinitionInfoAndBoundSpanResponse extends Response { body?: DefinitionInfoAndBoundSpan; } + /** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */ + type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse; /** * Definition response message. Gives text range for definition. */ @@ -2317,7 +2319,13 @@ declare namespace ts.server.protocol { * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. */ readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** + * Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled, + * member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined + * values, with insertion text to replace preceding `.` tokens with `?.`. + */ + readonly includeAutomaticOptionalChainCompletions?: boolean; + readonly importModuleSpecifierPreference?: "auto" | "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; readonly lazyConfiguredProjectsFromExternalProject?: boolean; readonly providePrefixAndSuffixTextForRename?: boolean; diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index 468fd47b888..f66fa953ac1 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -30,7 +30,7 @@ "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Декоратор может только декорировать реализацию метода, а не перегрузку.", "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Предложение default не может повторяться в операторе switch.", "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Экспорт по умолчанию можно использовать только в модуле в стиле ECMAScript.", - "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Утверждение определенного присваивания \"!\" запрещено в этом контексте.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Утверждение определенного назначения \"!\" запрещено в этом контексте.", "A_destructuring_declaration_must_have_an_initializer_1182": "Объявление деструктурирования должно включать инициализатор.", "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Для вызова динамического импорта в ES5/ES3 требуется конструктор \"Promise\". Объявите конструктор \"Promise\" или включите \"ES2015\" в параметр \"--lib\".", "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Вызов динамического импорта возвращает конструктор \"Promise\". Объявите конструктор \"Promise\" или включите \"ES2015\" в параметр \"--lib\".", @@ -103,8 +103,8 @@ "Add_all_missing_super_calls_95039": "Добавить все отсутствующие вызовы super", "Add_async_modifier_to_containing_function_90029": "Добавьте модификатор async в содержащую функцию", "Add_braces_to_arrow_function_95059": "Добавить скобки в стрелочную функцию", - "Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного присваивания к свойству \"{0}\"", - "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Добавить утверждения определенного присваивания ко всем неинициализированным свойствам", + "Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного назначения к свойству \"{0}\"", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Добавить утверждения определенного назначения ко всем неинициализированным свойствам", "Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\"", "Add_initializer_to_property_0_95019": "Добавить инициализатор к свойству \"{0}\"", "Add_initializers_to_all_uninitialized_properties_95027": "Добавить инициализаторы ко всем неинициализированным свойствам", @@ -130,7 +130,7 @@ "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Перечисление внешних констант не разрешено, если задан флаг \"--isolatedModules\".", "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Объявление окружающего модуля не может содержать относительное имя модуля.", "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Внешний модуль не может быть вложен в другие модули или пространства имен.", - "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Модуль AMD не может иметь несколько присваиваний имен.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Модуль AMD не может иметь несколько назначений имен.", "An_abstract_accessor_cannot_have_an_implementation_1318": "У абстрактного метода доступа не может быть реализации.", "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Метод доступа нельзя объявить в окружающем контексте.", "An_accessor_cannot_have_type_parameters_1094": "Метод доступа не может иметь параметры типа.", @@ -142,10 +142,10 @@ "An_async_iterator_must_have_a_next_method_2519": "В асинхронном итераторе должен быть метод next().", "An_element_access_expression_should_take_an_argument_1011": "Выражение доступа к элементу должно принимать аргумент.", "An_enum_member_cannot_have_a_numeric_name_2452": "Имя элемента перечисления не может быть числовым.", - "An_export_assignment_can_only_be_used_in_a_module_1231": "Присваивание экспорта может быть использовано только в модуле.", - "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Присваивание экспорта нельзя использовать в модуле с другими экспортированными элементами.", - "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Присваивание экспорта нельзя использовать в пространстве имен.", - "An_export_assignment_cannot_have_modifiers_1120": "Присваивание экспорта не может иметь модификаторы.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Назначение экспорта может быть использовано только в модуле.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Назначение экспорта нельзя использовать в модуле с другими экспортированными элементами.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Назначение экспорта нельзя использовать в пространстве имен.", + "An_export_assignment_cannot_have_modifiers_1120": "Назначение экспорта не может иметь модификаторы.", "An_export_declaration_can_only_be_used_in_a_module_1233": "Объявление экспорта может быть использовано только в модуле.", "An_export_declaration_cannot_have_modifiers_1193": "Объявление экспорта не может иметь модификаторы.", "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Расширенное escape-значение в Юникоде должно быть в пределах от 0x0 до 0x10FFFF включительно.", @@ -390,7 +390,7 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Экспериментальная поддержка для декораторов — это функция, которая будет изменена в будущем выпуске. Задайте параметр experimentalDecorators, чтобы удалить это предупреждение.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Явно указанный тип разрешения модуля: \"{0}\".", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Назначение экспорта невозможно использовать при разработке для модулей ECMAScript. Попробуйте использовать \"export default\" или другой формат модуля.", - "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Присваивание экспорта не поддерживается, если флаг \"--module\" имеет значение \"system\".", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Назначение экспорта не поддерживается, если флаг \"--module\" имеет значение \"system\".", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Объявление экспорта конфликтует с экспортированным объявлением \"{0}\".", "Export_declarations_are_not_permitted_in_a_namespace_1194": "Объявления экспорта не разрешены в пространстве имен.", "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Файл экспортированных внешних типизаций пакета \"{0}\" не является модулем. Обратитесь к автору пакета для обновления определения пакета.", @@ -441,7 +441,7 @@ "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Реализация функции отсутствует либо не идет сразу после объявления.", "Function_implementation_name_must_be_0_2389": "Имя реализации функции должно иметь значение \"{0}\".", "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Функция неявно имеет тип возвращаемого значения any, так как у нее нет заметки с типом возвращаемого значения, а также на нее прямо или косвенно указывает ссылка в одном из ее выражений \"return\".", - "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "В функции отсутствует завершающий оператор возвращаемого значения, а тип возвращаемого значения не включает undefined.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "В функции отсутствует завершающий оператор return, а тип возвращаемого значения не включает \"undefined\".", "Function_overload_must_be_static_2387": "Перегрузка функции должна быть статической.", "Function_overload_must_not_be_static_2388": "Перегрузка функции не должна быть статической.", "Generate_get_and_set_accessors_95046": "Создать методы доступа get и set", @@ -594,7 +594,7 @@ "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Не удалось найти входные данные в файле конфигурации \"{0}\". Указанные пути \"include\": \"{1}\", пути \"exclude\": \"{2}\".", "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Класс \"{0}\", не являющийся абстрактным, не реализует наследуемый абстрактный элемент \"{1}\" класса \"{2}\".", "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Выражение неабстрактного класса не реализует унаследованный абстрактный элемент \"{0}\" класса \"{1}\".", - "Not_all_code_paths_return_a_value_7030": "Не все пути кода возвращают значение.", + "Not_all_code_paths_return_a_value_7030": "Не все пути к коду возвращают значение.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Тип числового индекса \"{0}\" нельзя назначить типу строкового индекса \"{1}\".", "Numeric_separators_are_not_allowed_here_6188": "Числовые разделители здесь запрещены.", "Object_is_of_type_unknown_2571": "Объект имеет тип \"Неизвестный\".", @@ -714,7 +714,7 @@ "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Свойство \"{0}\" экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Свойство \"{0}\" типа \"{1}\" нельзя назначить типу числового индекса \"{2}\".", "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Свойство \"{0}\" типа \"{1}\" нельзя назначить типу строкового индекса \"{2}\".", - "Property_assignment_expected_1136": "Ожидалось присваивание свойства.", + "Property_assignment_expected_1136": "Ожидалось назначение свойства.", "Property_destructuring_pattern_expected_1180": "Ожидался шаблон деструктурирования свойства.", "Property_or_signature_expected_1131": "Ожидалось свойство или сигнатура.", "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Значение свойства может быть только строковым или числовым литералом, True, False, Null, объектным литералом либо литералом массива.", @@ -745,7 +745,7 @@ "Remove_unused_label_95053": "Удалить неиспользуемую метку", "Remove_variable_statement_90010": "Удалить оператор с переменной", "Replace_import_with_0_95015": "Замена импорта на \"{0}\".", - "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути кода в функции возвращают значение.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути к коду в функции возвращают значение.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Сообщать об ошибках для случаев передачи управления в операторе switch.", "Report_errors_in_js_files_8019": "Сообщать об ошибках в JS-файлах.", "Report_errors_on_unused_locals_6134": "Сообщать об ошибках в неиспользованных локальных переменных.", @@ -850,7 +850,7 @@ "The_character_set_of_the_input_files_6163": "Кодировка входных файлов.", "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Содержащая функция или текст модуля слишком велики для анализа потока управления.", "The_current_host_does_not_support_the_0_option_5001": "Текущий узел не поддерживает параметр \"{0}\".", - "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Выражение присваивания экспорта должно представлять собой идентификатор или полное имя в окружающем контексте.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Выражение назначения экспорта должно представлять собой идентификатор или полное имя в окружающем контексте.", "The_files_list_in_config_file_0_is_empty_18002": "Список \"files\" в файле конфигурации \"{0}\" пуст.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Первым параметром метода then класса promise должен быть обратный вызов.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Глобальный тип \"JSX.{0}\" не может иметь больше одного свойства.", @@ -1039,7 +1039,7 @@ "const_declarations_must_be_initialized_1155": "Объявления \"const\" должны быть инициализированы.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Инициализатор элементов перечисления const был вычислен в неконечное значение.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Инициализатор элементов перечисления const был вычислен в запрещенное значение NaN.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Перечисления const можно использовать только в выражениях доступа к свойству или индексу, а также в правой части объявления импорта, присваивания экспорта или запроса типа.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Перечисления const можно использовать только в выражениях доступа к свойству или индексу, а также в правой части объявления импорта, назначения экспорта или запроса типа.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Невозможно вызвать оператор delete с идентификатором в строгом режиме.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "удалить это — проект \"{0}\" не требует обновления, так как был собран ранее", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Объявления перечислений можно использовать только в TS-файле.", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 892fc74d391..dc52ec079ef 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -453,7 +453,7 @@ "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Oluşturucular yalnızca ECMEAScript 2015 veya üstü hedeflenirken kullanılabilir.", "Generic_type_0_requires_1_type_argument_s_2314": "'{0}' genel türü, {1} tür bağımsız değişkenini gerektiriyor.", "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "'{0}' genel türü {1} ile {2} arasında bağımsız değişken gerektirir.", - "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Genel tür oluşturma işlemi, fazla ayrıntılı ve büyük olasılıkla sınırsız.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Genel tür örneği oluşturma işlemi, fazla ayrıntılı ve büyük olasılıkla sınırsız.", "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Alıcı ve ayarlayıcı erişimcileri görünürlükte anlaşamıyor.", "Global_module_exports_may_only_appear_at_top_level_1316": "Genel modül dışarı aktarmaları yalnızca en üst düzeyde görünebilir.", "Global_module_exports_may_only_appear_in_declaration_files_1315": "Genel modül dışarı aktarmaları yalnızca bildirim dosyalarında görünebilir.", diff --git a/lib/tsc.js b/lib/tsc.js index 0b8d4130e00..253098e4d4d 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -66,19 +66,25 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook }; var ts; (function (ts) { - ts.versionMajorMinor = "3.7"; + ts.versionMajorMinor = "3.8"; ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); (function (ts) { - ts.emptyArray = []; - function createDictionaryObject() { - var map = Object.create(null); - map.__ = undefined; - delete map.__; - return map; + function tryGetNativeMap() { + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; } + ts.tryGetNativeMap = tryGetNativeMap; +})(ts || (ts = {})); +(function (ts) { + ts.emptyArray = []; + ts.Map = ts.tryGetNativeMap() || (function () { + if (typeof ts.createMapShim === "function") { + return ts.createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); function createMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createMap = createMap; function createMapFromEntries(entries) { @@ -91,7 +97,7 @@ var ts; } ts.createMapFromEntries = createMapFromEntries; function createMapFromTemplate(template) { - var map = new ts.MapCtr(); + var map = new ts.Map(); for (var key in template) { if (hasOwnProperty.call(template, key)) { map.set(key, template[key]); @@ -100,121 +106,6 @@ var ts; return map; } ts.createMapFromTemplate = createMapFromTemplate; - ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - function shimMap() { - var MapIterator = (function () { - function MapIterator(currentEntry, selector) { - this.currentEntry = currentEntry; - this.selector = selector; - } - MapIterator.prototype.next = function () { - while (this.currentEntry) { - var skipNext = !!this.currentEntry.skipNext; - this.currentEntry = this.currentEntry.nextEntry; - if (!skipNext) { - break; - } - } - if (this.currentEntry) { - return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false }; - } - else { - return { value: undefined, done: true }; - } - }; - return MapIterator; - }()); - return (function () { - function class_1() { - this.data = createDictionaryObject(); - this.size = 0; - this.firstEntry = {}; - this.lastEntry = this.firstEntry; - } - class_1.prototype.get = function (key) { - var entry = this.data[key]; - return entry && entry.value; - }; - class_1.prototype.set = function (key, value) { - if (!this.has(key)) { - this.size++; - var newEntry = { - key: key, - value: value - }; - this.data[key] = newEntry; - var previousLastEntry = this.lastEntry; - previousLastEntry.nextEntry = newEntry; - newEntry.previousEntry = previousLastEntry; - this.lastEntry = newEntry; - } - else { - this.data[key].value = value; - } - return this; - }; - class_1.prototype.has = function (key) { - return key in this.data; - }; - class_1.prototype.delete = function (key) { - if (this.has(key)) { - this.size--; - var entry = this.data[key]; - delete this.data[key]; - var previousEntry = entry.previousEntry; - previousEntry.nextEntry = entry.nextEntry; - if (entry.nextEntry) { - entry.nextEntry.previousEntry = previousEntry; - } - if (this.lastEntry === entry) { - this.lastEntry = previousEntry; - } - entry.previousEntry = undefined; - entry.nextEntry = previousEntry; - entry.skipNext = true; - return true; - } - return false; - }; - class_1.prototype.clear = function () { - this.data = createDictionaryObject(); - this.size = 0; - var firstEntry = this.firstEntry; - var currentEntry = firstEntry.nextEntry; - while (currentEntry) { - var nextEntry = currentEntry.nextEntry; - currentEntry.previousEntry = undefined; - currentEntry.nextEntry = firstEntry; - currentEntry.skipNext = true; - currentEntry = nextEntry; - } - firstEntry.nextEntry = undefined; - this.lastEntry = firstEntry; - }; - class_1.prototype.keys = function () { - return new MapIterator(this.firstEntry, function (key) { return key; }); - }; - class_1.prototype.values = function () { - return new MapIterator(this.firstEntry, function (_key, value) { return value; }); - }; - class_1.prototype.entries = function () { - return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; }); - }; - class_1.prototype.forEach = function (action) { - var iterator = this.entries(); - while (true) { - var iterResult = iterator.next(); - if (iterResult.done) { - break; - } - var _a = iterResult.value, key = _a[0], value = _a[1]; - action(value, key); - } - }; - return class_1; - }()); - } - ts.shimMap = shimMap; function length(array) { return array ? array.length : 0; } @@ -1552,20 +1443,6 @@ var ts; return str.indexOf(substring) !== -1; } ts.stringContains = stringContains; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; function removeMinAndVersionNumbers(fileName) { var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); @@ -1855,11 +1732,14 @@ var ts; if (isFlags) { var result = ""; var remainingFlags = value; - for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { - var _a = members[i], enumValue = _a[0], enumName = _a[1]; - if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; + if (enumValue > value) { + break; + } + if (enumValue !== 0 && enumValue & value) { + result = "" + result + (result ? "|" : "") + enumName; remainingFlags &= ~enumValue; - result = "" + enumName + (result ? "|" : "") + result; } } if (remainingFlags === 0) { @@ -1867,8 +1747,8 @@ var ts; } } else { - for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { - var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + for (var _b = 0, members_2 = members; _b < members_2.length; _b++) { + var _c = members_2[_b], enumValue = _c[0], enumName = _c[1]; if (enumValue === value) { return enumName; } @@ -1942,6 +1822,33 @@ var ts; ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; var isDebugInfoEnabled = false; + var extendedDebugModule; + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + Debug.formatControlFlowGraph = formatControlFlowGraph; + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { + Object.defineProperties(flowNode, { + __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, true); } }, + __debugToString: { value: function () { return formatControlFlowGraph(this); } } + }); + } + } + } + Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; function enableDebugInfo() { if (isDebugInfoEnabled) return; @@ -1981,6 +1888,18 @@ var ts; }); } } + try { + if (ts.sys && ts.sys.require) { + var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath())); + var result = ts.sys.require(basePath, "./compiler-debug"); + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch (_a) { + } isDebugInfoEnabled = true; } Debug.enableDebugInfo = enableDebugInfo; @@ -2102,8 +2021,6 @@ var ts; etwModule = undefined; } ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - var args = typeof process === "undefined" ? [] : process.argv; - ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(args)); })(ts || (ts = {})); var ts; (function (ts) { @@ -2406,6 +2323,7 @@ var ts; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped"; + ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); var TypeReferenceSerializationKind; @@ -2832,24 +2750,10 @@ var ts; } } ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; - function recursiveCreateDirectory(directoryPath, sys) { - var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); - if (shouldCreateParent) { - recursiveCreateDirectory(basePath, sys); - } - if (shouldCreateParent || !sys.directoryExists(directoryPath)) { - sys.createDirectory(directoryPath); - } - } function patchWriteFileEnsuringDirectory(sys) { var originalWriteFile = sys.writeFile; sys.writeFile = function (path, data, writeBom) { - var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); - if (directoryPath && !sys.directoryExists(directoryPath)) { - recursiveCreateDirectory(directoryPath, sys); - } - originalWriteFile.call(sys, path, data, writeBom); + return ts.writeFileEnsuringDirectories(path, data, !!writeBom, function (path, data, writeByteOrderMark) { return originalWriteFile.call(sys, path, data, writeByteOrderMark); }, function (path) { return sys.createDirectory(path); }, function (path) { return sys.directoryExists(path); }); }; } ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory; @@ -2983,6 +2887,15 @@ var ts; bufferFrom: bufferFrom, base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + require: function (baseDir, moduleName) { + try { + var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath: modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error: error }; + } + } }; return nodeSystem; function enableCPUProfiler(path, cb) { @@ -3486,6 +3399,468 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + function isAnyDirectorySeparator(charCode) { + return charCode === 47 || charCode === 92; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function isVolumeCharacter(charCode) { + return (charCode >= 97 && charCode <= 122) || + (charCode >= 65 && charCode <= 90); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58) + return start + 1; + if (ch0 === 37 && url.charCodeAt(start + 1) === 51) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 || ch2 === 65) + return start + 3; + } + return -1; + } + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + if (ch0 === 47 || ch0 === 92) { + if (path.charCodeAt(1) !== ch0) + return 1; + var p1 = path.indexOf(ch0 === 47 ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; + return p1 + 1; + } + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 || ch2 === 92) + return 3; + if (path.length === 2) + return 2; + } + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47) { + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); + } + return ~path.length; + } + return 0; + } + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArrays([root], rest); + } + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0) { + return result; + } + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0) { + return result_1; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArrays([""], relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; +})(ts || (ts = {})); +var ts; (function (ts) { function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid) { return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid }; @@ -3509,7 +3884,7 @@ var ts; An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), - An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), @@ -3717,7 +4092,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd_1323", "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -3753,6 +4128,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"), 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), @@ -3880,7 +4256,6 @@ var ts; Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), @@ -4050,8 +4425,8 @@ var ts; JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2610, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_proper_2610", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member property."), - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2611, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_access_2611", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member accessor."), + _0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property: diag(2610, ts.DiagnosticCategory.Error, "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610", "'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property."), + _0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor: diag(2611, ts.DiagnosticCategory.Error, "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611", "'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor."), Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), @@ -4274,6 +4649,8 @@ var ts; Parameter_0_of_accessor_has_or_is_using_private_name_1: diag(4106, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106", "Parameter '{0}' of accessor has or is using private name '{1}'."), Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2: diag(4107, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107", "Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'."), Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4108, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108", "Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named."), + Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), + Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -4281,6 +4658,7 @@ var ts; Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Unknown_compiler_option_0_Did_you_mean_1: diag(5025, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"), Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), @@ -4311,6 +4689,7 @@ var ts; 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}'?"), 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."), @@ -4357,7 +4736,7 @@ var ts; Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has an unsupported extension. The only supported extensions are {1}."), Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), @@ -4565,6 +4944,8 @@ var ts; 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."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), + File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -4668,6 +5049,7 @@ var ts; Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), + Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"), Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), @@ -6684,7 +7066,7 @@ var ts; } ts.getDeclarationOfKind = getDeclarationOfKind; function createUnderscoreEscapedMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; function hasEntries(map) { @@ -6738,13 +7120,6 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -7450,6 +7825,11 @@ var ts; break; case 201: return getErrorSpanForArrowFunction(sourceFile, node); + case 275: + case 276: + var start = ts.skipTrivia(sourceFile.text, node.pos); + var end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return ts.createTextSpanFromBounds(start, end); } if (errorNode === undefined) { return getSpanOfTokenAtPosition(sourceFile, node.pos); @@ -8191,7 +8571,7 @@ var ts; (node.typeArguments[0].kind === 142 || node.typeArguments[0].kind === 139); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 195) { return false; } @@ -8203,7 +8583,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -8389,13 +8769,6 @@ var ts; isBindableStaticNameExpression(expr.arguments[0], true); } ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; - function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { - return isLiteralLikeElementAccess(node) - && ((!excludeThisKeyword && node.expression.kind === 103) || - isEntityNameExpression(node.expression) || - isBindableStaticElementAccessExpression(node.expression, true)); - } - ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression; function isLiteralLikeAccess(node) { return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node); } @@ -8410,6 +8783,13 @@ var ts; || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; + function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { + return isLiteralLikeElementAccess(node) + && ((!excludeThisKeyword && node.expression.kind === 103) || + isEntityNameExpression(node.expression) || + isBindableStaticAccessExpression(node.expression, true)); + } + ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression; function isBindableStaticNameExpression(node, excludeThisKeyword) { return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword); } @@ -8438,7 +8818,7 @@ var ts; if (expr.operatorToken.kind !== 62 || !isAccessExpression(expr.left)) { return 0; } - if (isBindableStaticNameExpression(expr.left.expression) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + if (isBindableStaticNameExpression(expr.left.expression, true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { return 6; } return getAssignmentDeclarationPropertyAccessKind(expr.left); @@ -8486,11 +8866,14 @@ var ts; nextToLast = nextToLast.expression; } var id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + isBindableStaticAccessExpression(lhs)) { return 1; } - return 5; + if (isBindableStaticNameExpression(lhs, true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs) && lhs.expression.kind !== 103)) { + return 5; + } } return 0; } @@ -9709,7 +10092,7 @@ var ts; ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); var extensionless = ts.removeFileExtension(relativePath); @@ -9781,6 +10164,23 @@ var ts; }, sourceFiles); } ts.writeFile = writeFile; + function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists); + createDirectory(directoryPath); + } + } + function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) { + try { + writeFile(path, data, writeByteOrderMark); + } + catch (_a) { + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists); + writeFile(path, data, writeByteOrderMark); + } + } + ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories; function getLineOfLocalPosition(currentSourceFile, pos) { return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; } @@ -10159,6 +10559,23 @@ var ts; return node.kind === 75 || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function getFirstIdentifier(node) { + switch (node.kind) { + case 75: + return node; + case 152: + do { + node = node.left; + } while (node.kind !== 75); + return node; + case 193: + do { + node = node.expression; + } while (node.kind !== 75); + return node; + } + } + ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { return node.kind === 75 || node.kind === 103 || node.kind === 193 && isDottedName(node.expression) || @@ -10587,20 +11004,6 @@ var ts; }); } ts.mutateMap = mutateMap; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; function isAbstractConstructorType(type) { return !!(getObjectFlags(type) & 16) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); } @@ -10626,7 +11029,7 @@ var ts; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { @@ -11488,11 +11891,31 @@ var ts; } ts.isCallChain = isCallChain; function isOptionalChain(node) { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + var kind = node.kind; + return !!(node.flags & 32) && + (kind === 193 + || kind === 194 + || kind === 195); } ts.isOptionalChain = isOptionalChain; + function isOptionalChainRoot(node) { + return isOptionalChain(node) && !!node.questionDotToken; + } + ts.isOptionalChainRoot = isOptionalChainRoot; + function isExpressionOfOptionalChainRoot(node) { + return isOptionalChainRoot(node.parent) && node.parent.expression === node; + } + ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot; + function isOutermostOptionalChain(node) { + return !isOptionalChain(node.parent) + || isOptionalChainRoot(node.parent) + || node !== node.parent.expression; + } + ts.isOutermostOptionalChain = isOutermostOptionalChain; + function isNullishCoalesce(node) { + return node.kind === 208 && node.operatorToken.kind === 60; + } + ts.isNullishCoalesce = isNullishCoalesce; function isNewExpression(node) { return node.kind === 196; } @@ -12647,10 +13070,6 @@ var ts; return node.kind === 162; } ts.isGetAccessor = isGetAccessor; - function isOptionalChainRoot(node) { - return ts.isOptionalChain(node) && !!node.questionDotToken; - } - ts.isOptionalChainRoot = isOptionalChainRoot; function hasJSDocNodes(node) { var jsDoc = node.jsDoc; return !!jsDoc && jsDoc.length > 0; @@ -12725,7 +13144,12 @@ var ts; this.checker = checker; } } - function Signature() { } + function Signature(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } function Node(kind, pos, end) { this.pos = pos; this.end = end; @@ -12998,195 +13422,6 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - ts.directorySeparator = "/"; - var altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - function normalizeSlashes(path) { - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - function isVolumeCharacter(charCode) { - return (charCode >= 97 && charCode <= 122) || - (charCode >= 65 && charCode <= 90); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58) - return start + 1; - if (ch0 === 37 && url.charCodeAt(start + 1) === 51) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 || ch2 === 65) - return start + 3; - } - return -1; - } - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - if (ch0 === 47 || ch0 === 92) { - if (path.charCodeAt(1) !== ch0) - return 1; - var p1 = path.indexOf(ch0 === 47 ? ts.directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; - return p1 + 1; - } - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 || ch2 === 92) - return 3; - if (path.length === 2) - return 2; - } - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47) { - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); - } - return ~path.length; - } - return 0; - } - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - function normalizePath(path) { - return ts.resolvePath(path); - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - path = ts.removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); - } - ts.convertToRelativePath = convertToRelativePath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArrays([root], rest); - } - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = ts.combinePaths(currentDirectory, path); - var rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - ts.getPathComponents = getPathComponents; - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var result = ts.createMap(); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { @@ -13203,214 +13438,23 @@ var ts; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { aParts.pop(); bParts.pop(); } - return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; } function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); } })(ts || (ts = {})); (function (ts) { - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); - var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArrays([""], relative, components); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - function ensurePathIsNonModuleName(path) { - return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function getBaseFileName(path, extensions, ignoreCase) { - path = ts.normalizeSlashes(path); - var rootLength = ts.getRootLength(path); - if (rootLength === path.length) - return ""; - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = ts.normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = ts.normalizeSlashes(relativePath); - if (!path || ts.getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - var combined = ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : ts.normalizeSlashes(path); - var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.resolvePath = resolvePath; - function hasTrailingDirectorySeparator(path) { - if (path.length === 0) - return false; - var ch = path.charCodeAt(path.length - 1); - return ch === 47 || ch === 92; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0; - if (a === undefined) - return -1; - if (b === undefined) - return 1; - var aRoot = a.substring(0, ts.getRootLength(a)); - var bRoot = b.substring(0, ts.getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0) { - return result; - } - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); - var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_1 = componentComparer(aComponents[i], bComponents[i]); - if (result_1 !== 0) { - return result_1; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); - var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function isDirectorySeparator(charCode) { - return charCode === 47 || charCode === 92; - } function stripLeadingDirectorySeparator(s) { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); @@ -13426,10 +13470,6 @@ var ts; return "\\" + match; } var wildcardCharCodes = [42, 63]; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -13484,7 +13524,7 @@ var ts; if (usage !== "exclude" && lastComponent === "**") { return undefined; } - components[0] = removeTrailingDirectorySeparator(components[0]); + components[0] = ts.removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); } @@ -13536,7 +13576,7 @@ var ts; function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); + var absolutePath = ts.combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), @@ -13562,7 +13602,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -13572,8 +13612,8 @@ var ts; visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) @@ -13600,8 +13640,8 @@ var ts; } for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { visitDirectory(name, absoluteName, depth); @@ -13616,12 +13656,12 @@ var ts; var includeBasePaths = []; for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { var include = includes_1[_i]; - var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include)); includeBasePaths.push(getIncludeBasePath(absolute)); } includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -13635,9 +13675,9 @@ var ts; function getIncludeBasePath(absolute) { var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { - return !hasExtension(absolute) + return !ts.hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -13699,10 +13739,6 @@ var ts; return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJSFileExtension = hasJSFileExtension; - function hasJSOrJsonFileExtension(fileName) { - return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); - } - ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; function hasTSFileExtension(fileName) { return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -13772,14 +13808,9 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return changeAnyExtension(path, newExtension, extensionsToRemove, false); + return ts.changeAnyExtension(path, newExtension, extensionsToRemove, false); } ts.changeExtension = changeExtension; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; function tryParsePattern(pattern) { ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); var indexOfStar = pattern.indexOf("*"); @@ -13814,34 +13845,6 @@ var ts; return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") - extensions = [extensions]; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -14865,6 +14868,9 @@ var ts; function doInYieldAndAwaitContext(func) { return doInsideOfContext(8192 | 32768, func); } + function doOutsideOfYieldAndAwaitContext(func) { + return doOutsideOfContext(8192 | 32768, func); + } function inContext(flags) { return (contextFlags & flags) !== 0; } @@ -18315,9 +18321,7 @@ var ts; node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); - node.initializer = ts.hasModifier(node, 32) - ? allowInAnd(parseInitializer) - : doOutsideOfContext(8192 | 4096, parseInitializer); + node.initializer = doOutsideOfContext(8192 | 32768 | 4096, parseInitializer); parseSemicolon(); return finishNode(node); } @@ -18561,7 +18565,7 @@ var ts; parseExpected(87); node.name = parseIdentifier(); if (parseExpected(18)) { - node.members = parseDelimitedList(6, parseEnumMember); + node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6, parseEnumMember); }); parseExpected(19); } else { @@ -20280,6 +20284,15 @@ var ts; isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, { name: "target", shortName: "t", @@ -21076,8 +21089,7 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { - var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; + function parseCommandLineWorker(getOptionNameMap, diagnostics, commandLine, readFile) { var options = {}; var fileNames = []; var errors = []; @@ -21103,7 +21115,7 @@ var ts; } else { if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); + errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -21136,7 +21148,13 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); + var possibleOption = ts.getSpellingSuggestion(s, ts.optionDeclarations, function (opt) { return "--" + opt.name; }); + if (possibleOption) { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownDidYouMeanDiagnostic, s, possibleOption.name)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownOptionDiagnostic, s)); + } } } else { @@ -21179,11 +21197,13 @@ var ts; parseStrings(args); } } + var compilerOptionsDefaultDiagnostics = { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument + }; function parseCommandLine(commandLine, readFile) { - return parseCommandLineWorker(getOptionNameMap, [ - ts.Diagnostics.Unknown_compiler_option_0, - ts.Diagnostics.Compiler_option_0_expects_an_argument - ], commandLine, readFile); + return parseCommandLineWorker(getOptionNameMap, compilerOptionsDefaultDiagnostics, commandLine, readFile); } ts.parseCommandLine = parseCommandLine; function getOptionFromName(optionName, allowShort) { @@ -21205,10 +21225,11 @@ var ts; function parseBuildCommand(args) { var buildOptionNameMap; var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; - var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ - ts.Diagnostics.Unknown_build_option_0, - ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 - ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + }, args), options = _a.options, projects = _a.fileNames, errors = _a.errors; var buildOptions = options; if (projects.length === 0) { projects.push("."); @@ -21236,92 +21257,7 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - function printVersion() { - ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); - } - ts.printVersion = printVersion; - function printHelp(optionsList, syntaxPrefix) { - if (syntaxPrefix === void 0) { syntaxPrefix = ""; } - var output = []; - var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); - var syntax = makePadding(marginLength - syntaxLength); - syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; - output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); - output.push(ts.sys.newLine + ts.sys.newLine); - var padding = makePadding(marginLength); - output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); - output.push(padding + "tsc @args.txt" + ts.sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); - output.push(ts.sys.newLine); - output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); - marginLength = 0; - var usageColumn = []; - var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); - for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { - var option = optionsList_1[_i]; - if (!option.description) { - continue; - } - var usageText_1 = " "; - if (option.shortName) { - usageText_1 += "-" + option.shortName; - usageText_1 += getParamType(option); - usageText_1 += ", "; - } - usageText_1 += "--" + option.name; - usageText_1 += getParamType(option); - usageColumn.push(usageText_1); - var description = void 0; - if (option.name === "lib") { - description = getDiagnosticText(option.description); - var element = option.element; - var typeMap = element.type; - optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); - } - else { - description = getDiagnosticText(option.description); - } - descriptionColumn.push(description); - marginLength = Math.max(usageText_1.length, marginLength); - } - var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; - var kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { - var kind = kindsList_1[_a]; - output.push(kind + " "); - } - output.push(ts.sys.newLine); - } - } - for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { - var line = output_1[_b]; - ts.sys.write(line); - } - return; - function getParamType(option) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - } - ts.printHelp = printHelp; + ts.getDiagnosticText = getDiagnosticText; function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache) { var configFileText; try { @@ -21387,19 +21323,28 @@ var ts; name: "compilerOptions", type: "object", elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1 + }, }, { name: "typingOptions", type: "object", elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 + }, }, { name: "typeAcquisition", type: "object", elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 + } }, { name: "extends", @@ -21455,7 +21400,7 @@ var ts; function isRootOptionMap(knownOptions) { return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } - function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; @@ -21472,8 +21417,19 @@ var ts; var textOfKey = ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; - if (keyText && extraKeyDiagnosticMessage && !option) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + if (keyText && extraKeyDiagnostics && !option) { + if (knownOptions) { + var possibleOption = ts.getSpellingSuggestion(keyText, ts.arrayFrom(knownOptions.keys()), ts.identity); + if (possibleOption) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownDidYouMeanDiagnostic, keyText, possibleOption)); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } } var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { @@ -21544,8 +21500,8 @@ var ts; reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; if (option) { - var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; - return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName); } else { return convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined); @@ -21591,7 +21547,7 @@ var ts; } function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign(__assign({ compilerOptions: __assign(__assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; @@ -21612,12 +21568,12 @@ var ts; return undefined; return specs; } - function matchesSpecs(path, includeSpecs, excludeSpecs) { + function matchesSpecs(path, includeSpecs, excludeSpecs, host) { if (!includeSpecs) return function (_) { return true; }; - var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); - var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); - var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; @@ -21775,6 +21731,34 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + var result = {}; + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name in options) { + if (ts.hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; + function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option) { + if (option.type === "list") { + var values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value); + } + } + return value; + } function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) { return parseJsonConfigFileContentWorker(json, undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); } @@ -22125,7 +22109,7 @@ var ts; } function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); - convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, compilerOptionsDefaultDiagnostics, errors); if (configFileName) { options.configFilePath = ts.normalizeSlashes(configFileName); } @@ -22137,10 +22121,14 @@ var ts; function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); - convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + var diagnostics = { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1, + }; + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, diagnostics, errors); return options; } - function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnostics, errors) { if (!jsonOptions) { return; } @@ -22151,7 +22139,13 @@ var ts; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } else { - errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + var possibleOption = ts.getSpellingSuggestion(id, optionDeclarations, function (opt) { return opt.name; }); + if (possibleOption) { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownDidYouMeanDiagnostic, id, possibleOption.name)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownOptionDiagnostic, id)); + } } } } @@ -22187,7 +22181,7 @@ var ts; } function normalizeNonListOptionValue(option, basePath, value) { if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + value = ts.getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } @@ -23604,7 +23598,10 @@ var ts; } return 1; } - var flowNodeCreated = ts.identity; + function initFlowNode(node) { + ts.Debug.attachFlowNodeDebugInfo(node); + return node; + } var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -23632,6 +23629,7 @@ var ts; var currentReturnTarget; var currentTrueTarget; var currentFalseTarget; + var currentExceptionTarget; var preSwitchCaseFlow; var activeLabels; var hasExplicitReturn; @@ -23656,6 +23654,8 @@ var ts; symbolCount = 0; skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); + ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); + ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -23678,6 +23678,7 @@ var ts; currentReturnTarget = undefined; currentTrueTarget = undefined; currentFalseTarget = undefined; + currentExceptionTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; emitFlags = 0; @@ -23906,27 +23907,27 @@ var ts; blockScopeContainer.locals = undefined; } if (containerFlags & 4) { - var saveFlowNodeCreated = flowNodeCreated; var saveCurrentFlow = currentFlow; var saveBreakTarget = currentBreakTarget; var saveContinueTarget = currentContinueTarget; var saveReturnTarget = currentReturnTarget; + var saveExceptionTarget = currentExceptionTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node); if (!isIIFE) { - currentFlow = { flags: 2 }; + currentFlow = initFlowNode({ flags: 2 }); if (containerFlags & (16 | 128)) { currentFlow.node = node; } } currentReturnTarget = isIIFE || node.kind === 161 ? createBranchLabel() : undefined; + currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = ts.identity; bindChildren(node); node.flags &= ~2816; if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { @@ -23951,9 +23952,9 @@ var ts; currentBreakTarget = saveBreakTarget; currentContinueTarget = saveContinueTarget; currentReturnTarget = saveReturnTarget; + currentExceptionTarget = saveExceptionTarget; activeLabels = saveActiveLabels; hasExplicitReturn = saveHasExplicitReturn; - flowNodeCreated = saveFlowNodeCreated; } else if (containerFlags & 64) { seenThisKeyword = false; @@ -24094,9 +24095,6 @@ var ts; case 309: bindJSDocTypeAlias(node); break; - case 307: - bindJSDocClassTag(node); - break; case 288: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); @@ -24135,9 +24133,8 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 || expr.kind === 103 || expr.kind === 101 || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && - ts.isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + ts.isOptionalChain(expr); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -24194,10 +24191,10 @@ var ts; return isNarrowableReference(expr); } function createBranchLabel() { - return { flags: 4, antecedents: undefined }; + return initFlowNode({ flags: 4, antecedents: undefined }); } function createLoopLabel() { - return { flags: 8, antecedents: undefined }; + return initFlowNode({ flags: 8, antecedents: undefined }); } function setFlowNodeReferenced(flow) { flow.flags |= flow.flags & 1024 ? 2048 : 1024; @@ -24215,36 +24212,32 @@ var ts; if (!expression) { return flags & 32 ? antecedent : unreachableFlow; } - if (expression.kind === 105 && flags & 64 || - expression.kind === 90 && flags & 32) { - if (!ts.isOptionalChainRoot(expression.parent)) { - return unreachableFlow; - } + if ((expression.kind === 105 && flags & 64 || + expression.kind === 90 && flags & 32) && + !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) { + return unreachableFlow; } if (!isNarrowingExpression(expression)) { return antecedent; } setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: flags, antecedent: antecedent, node: expression }); + return initFlowNode({ flags: flags, antecedent: antecedent, node: expression }); } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { - return antecedent; - } setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 128, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd }); + return initFlowNode({ flags: 128, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd }); } - function createFlowAssignment(antecedent, node) { + function createFlowMutation(flags, antecedent, node) { setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 16, antecedent: antecedent, node: node }); + var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node }); + if (currentExceptionTarget) { + addAntecedent(currentExceptionTarget, result); + } + return result; } function createFlowCall(antecedent, node) { setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 512, antecedent: antecedent, node: node }); - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 256, antecedent: antecedent, node: node }); + return initFlowNode({ flags: 512, antecedent: antecedent, node: node }); } function finishFlowLabel(flow) { var antecedents = flow.antecedents; @@ -24304,7 +24297,7 @@ var ts; } function bindCondition(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); - if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && isOutermostOptionalChain(node))) { + if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) { addAntecedent(trueTarget, createFlowCondition(32, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64, currentFlow, node)); } @@ -24433,46 +24426,25 @@ var ts; } function bindTryStatement(node) { var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - var tryPriors = []; - var oldFlowNodeCreated = flowNodeCreated; - if (node.catchClause || node.finallyBlock) { - flowNodeCreated = function (node) { return (tryPriors.push(node), node); }; - } + var saveExceptionTarget = currentExceptionTarget; + currentExceptionTarget = createBranchLabel(); + addAntecedent(currentExceptionTarget, currentFlow); bind(node.tryBlock); - flowNodeCreated = oldFlowNodeCreated; addAntecedent(preFinallyLabel, currentFlow); var flowAfterTry = currentFlow; var flowAfterCatch = unreachableFlow; if (node.catchClause) { - currentFlow = preTryFlow; - if (tryPriors.length) { - var preCatchFlow = createBranchLabel(); - addAntecedent(preCatchFlow, currentFlow); - for (var _i = 0, tryPriors_1 = tryPriors; _i < tryPriors_1.length; _i++) { - var p = tryPriors_1[_i]; - addAntecedent(preCatchFlow, p); - } - currentFlow = finishFlowLabel(preCatchFlow); - } + currentFlow = finishFlowLabel(currentExceptionTarget); + currentExceptionTarget = createBranchLabel(); + addAntecedent(currentExceptionTarget, currentFlow); bind(node.catchClause); addAntecedent(preFinallyLabel, currentFlow); flowAfterCatch = currentFlow; } + var exceptionTarget = finishFlowLabel(currentExceptionTarget); + currentExceptionTarget = saveExceptionTarget; if (node.finallyBlock) { - var preFinallyPrior = preTryFlow; - if (!node.catchClause) { - if (tryPriors.length) { - var preFinallyFlow_1 = createBranchLabel(); - addAntecedent(preFinallyFlow_1, preTryFlow); - for (var _a = 0, tryPriors_2 = tryPriors; _a < tryPriors_2.length; _a++) { - var p = tryPriors_2[_a]; - addAntecedent(preFinallyFlow_1, p); - } - preFinallyPrior = finishFlowLabel(preFinallyFlow_1); - } - } - var preFinallyFlow = { flags: 4096, antecedent: preFinallyPrior, lock: {} }; + var preFinallyFlow = initFlowNode({ flags: 4096, antecedent: exceptionTarget, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); @@ -24484,7 +24456,7 @@ var ts; } } if (!(currentFlow.flags & 1)) { - var afterFinallyFlow = flowNodeCreated({ flags: 8192, antecedent: currentFlow }); + var afterFinallyFlow = initFlowNode({ flags: 8192, antecedent: currentFlow }); preFinallyFlow.lock = afterFinallyFlow; currentFlow = afterFinallyFlow; } @@ -24515,6 +24487,7 @@ var ts; var savedSubtreeTransformFlags = subtreeTransformFlags; subtreeTransformFlags = 0; var clauses = node.clauses; + var isNarrowingSwitch = isNarrowingExpression(node.parent.expression); var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { var clauseStart = i; @@ -24523,14 +24496,14 @@ var ts; i++; } var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | 536870912; @@ -24591,7 +24564,7 @@ var ts; } function bindAssignmentTargetFlow(node) { if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); + currentFlow = createFlowMutation(16, currentFlow, node); } else if (node.kind === 191) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { @@ -24672,7 +24645,7 @@ var ts; if (operator === 62 && node.left.kind === 194) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); + currentFlow = createFlowMutation(256, currentFlow, node); } } } @@ -24708,7 +24681,7 @@ var ts; } } else { - currentFlow = createFlowAssignment(currentFlow, node); + currentFlow = createFlowMutation(16, currentFlow, node); } } function bindVariableDeclarationFlow(node) { @@ -24730,12 +24703,9 @@ var ts; addDeclarationToSymbol(host.symbol, host, 32); } } - function isOutermostOptionalChain(node) { - return !ts.isOptionalChain(node.parent) || ts.isOptionalChainRoot(node.parent) || node !== node.parent.expression; - } function bindOptionalExpression(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); - if (!ts.isOptionalChain(node) || isOutermostOptionalChain(node)) { + if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) { addAntecedent(trueTarget, createFlowCondition(32, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64, currentFlow, node)); } @@ -24762,7 +24732,7 @@ var ts; currentFlow = finishFlowLabel(preChainLabel); } doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget); - if (isOutermostOptionalChain(node)) { + if (ts.isOutermostOptionalChain(node)) { addAntecedent(trueTarget, createFlowCondition(32, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64, currentFlow, node)); } @@ -24803,7 +24773,7 @@ var ts; if (node.expression.kind === 193) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); + currentFlow = createFlowMutation(256, currentFlow, node); } } } @@ -25046,7 +25016,7 @@ var ts; var host = ts.getJSDocHost(typeAlias); container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1); }) || file; blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: 2 }; + currentFlow = initFlowNode({ flags: 2 }); parent = typeAlias; bind(typeAlias.typeExpression); var declName = ts.getNameOfDeclaration(typeAlias); @@ -25058,7 +25028,12 @@ var ts; switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) { case 1: case 2: - container = file; + if (!ts.isExternalOrCommonJsModule(file)) { + container = undefined; + } + else { + container = file; + } break; case 4: container = declName.parent.expression; @@ -25072,7 +25047,9 @@ var ts; case 0: return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration"); } - declareModuleMember(typeAlias, 524288, 788968); + if (container) { + declareModuleMember(typeAlias, 524288, 788968); + } container = oldContainer; } } @@ -25402,6 +25379,8 @@ var ts; case 302: case 185: return bindAnonymousTypeWorker(node); + case 307: + return bindJSDocClassTag(node); case 192: return bindObjectLiteralExpression(node); case 200: @@ -25599,7 +25578,8 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 : 4 | 1048576 | 512; - declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864, 0); + var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864, 0); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -25614,7 +25594,7 @@ var ts; constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); } } - if (constructorSymbol) { + if (constructorSymbol && constructorSymbol.valueDeclaration) { constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); if (ts.hasDynamicName(node)) { bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol); @@ -25681,6 +25661,9 @@ var ts; } function bindObjectDefinePrototypeProperty(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol) { + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, true); } function bindPrototypePropertyAssignment(lhs, parent) { @@ -25738,7 +25721,7 @@ var ts; } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32); } return namespaceSymbol; @@ -26289,7 +26272,8 @@ var ts; || ts.hasModifier(node, 2270) || node.typeParameters || node.type - || !node.body) { + || !node.body + || node.questionToken) { transformFlags |= 1; } if (subtreeFlags & 8192) { @@ -26320,7 +26304,7 @@ var ts; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 1048576; - if (ts.some(node.decorators) || ts.hasModifier(node, 2270) || node.type) { + if (ts.some(node.decorators) || ts.hasModifier(node, 2270) || node.type || node.questionToken) { transformFlags |= 1; } if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { @@ -27000,11 +26984,11 @@ var ts; undefinedSymbol.declarations = []; var globalThisSymbol = createSymbol(1536, "globalThis", 8); globalThisSymbol.exports = globals; + globalThisSymbol.declarations = []; globals.set(globalThisSymbol.escapedName, globalThisSymbol); var argumentsSymbol = createSymbol(4, "arguments"); var requireSymbol = createSymbol(4, "require"); var apparentArgumentCount; - var pooledOptionalTypeResult = { isOptional: false, type: undefined }; var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, @@ -27118,9 +27102,9 @@ var ts; }, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (nodeIn) { + getContextualType: function (nodeIn, contextFlags) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); @@ -27169,7 +27153,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments), getAmbientModules: getAmbientModules, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { @@ -27292,10 +27276,10 @@ var ts; var errorType = createIntrinsicType(1, "error"); var unknownType = createIntrinsicType(2, "unknown"); var undefinedType = createIntrinsicType(32768, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768, "undefined", 262144); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768, "undefined", 524288); var optionalType = createIntrinsicType(32768, "undefined"); var nullType = createIntrinsicType(65536, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536, "null", 262144); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536, "null", 524288); var stringType = createIntrinsicType(4, "string"); var numberType = createIntrinsicType(8, "number"); var bigintType = createIntrinsicType(64, "bigint"); @@ -27319,7 +27303,7 @@ var ts; var voidType = createIntrinsicType(16384, "void"); var neverType = createIntrinsicType(131072, "never"); var silentNeverType = createIntrinsicType(131072, "never"); - var nonInferrableType = createIntrinsicType(131072, "never", 1048576); + var nonInferrableType = createIntrinsicType(131072, "never", 2097152); var implicitNeverType = createIntrinsicType(131072, "never"); var unreachableNeverType = createIntrinsicType(131072, "never"); var nonPrimitiveType = createIntrinsicType(67108864, "object"); @@ -27335,7 +27319,7 @@ var ts; var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - anyFunctionType.objectFlags |= 1048576; + anyFunctionType.objectFlags |= 2097152; 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); @@ -27344,10 +27328,10 @@ var ts; markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); var noTypePredicate = createTypePredicate(1, "<>", 0, anyType); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, undefined, 0, false, false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, false, false); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, 0); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, undefined, 0, 0); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, 0); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, 0); var enumNumberIndexInfo = createIndexInfo(stringType, true); var iterationTypesCache = ts.createMap(); var noIterationTypes = { @@ -27491,7 +27475,7 @@ var ts; var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } } } @@ -27501,7 +27485,7 @@ var ts; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -28736,7 +28720,7 @@ var ts; var namespaceMeaning = 1920 | (ts.isInJSFile(name) ? meaning & 111551 : 0); var symbol; if (name.kind === 75) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true); if (!symbol) { @@ -28834,7 +28818,12 @@ var ts; return undefined; } var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl); - return init && getSymbolOfNode(init) || undefined; + if (init) { + var initSymbol = getSymbolOfNode(init); + if (initSymbol) { + return mergeJSSymbols(initSymbol, symbol); + } + } } function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); @@ -29224,8 +29213,8 @@ var ts; } function findConstructorDeclaration(node) { var members = node.members; - for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { - var member = members_2[_i]; + for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { + var member = members_3[_i]; if (member.kind === 161 && ts.nodeIsPresent(member.body)) { return member; } @@ -29569,7 +29558,7 @@ var ts; else { meaning = 788968; } - var firstIdentifier = getFirstIdentifier(entityName); + var firstIdentifier = ts.getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); return (symbol && hasVisibleDeclarations(symbol, true)) || { accessibility: 1, @@ -30047,7 +30036,6 @@ var ts; else if (context.flags & 2048 && type.symbol.valueDeclaration && ts.isClassLike(type.symbol.valueDeclaration) && - ts.findAncestor(type.symbol.valueDeclaration, function (d) { return d === ts.getSourceFileOfNode(context.enclosingDeclaration); }) && !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } @@ -30201,9 +30189,9 @@ var ts; } } } - var propertyName = symbolToName(propertySymbol, context, 111551, true); - context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; + var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(57) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768); }), 0); @@ -30391,7 +30379,7 @@ var ts; function trackComputedName(accessExpression, enclosingDeclaration, context) { if (!context.tracker.trackSymbol) return; - var firstIdentifier = getFirstIdentifier(accessExpression); + var firstIdentifier = ts.getFirstIdentifier(accessExpression); var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 | 1048576, undefined, undefined, true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551); @@ -30732,21 +30720,33 @@ var ts; } } } + function isSingleQuotedStringNamed(d) { + var name = ts.getNameOfDeclaration(d); + if (name && ts.isStringLiteral(name) && (name.singleQuote || + (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, false), "'")))) { + return true; + } + return false; + } function getPropertyNameNodeForSymbol(symbol, context) { - var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context); + var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed); + var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote); if (fromNameType) { return fromNameType; } + if (ts.isKnownSymbol(symbol)) { + return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3))); + } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); - return createPropertyNameNodeForIdentifierOrLiteral(rawName); + return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote); } - function getPropertyNameNodeForSymbolFromNameType(symbol, context) { + function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) { var nameType = symbol.nameType; if (nameType) { if (nameType.flags & 384) { var name = "" + nameType.value; if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { - return ts.createLiteral(name); + return ts.createLiteral(name, !!singleQuote); } if (isNumericLiteralName(name) && ts.startsWith(name, "-")) { return ts.createComputedPropertyName(ts.createLiteral(+name)); @@ -30758,8 +30758,8 @@ var ts; } } } - function createPropertyNameNodeForIdentifierOrLiteral(name) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name); + function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -30782,7 +30782,7 @@ var ts; var visitedSymbols = ts.createMap(); var deferredPrivates; var oldcontext = context; - context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.mapMap(symbolTable, function (_symbol, name) { return [ts.unescapeLeadingUnderscores(name), true]; }), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { + context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { var accessibleResult = isSymbolAccessible(sym, decl, meaning, false); if (accessibleResult.accessibility === 0) { var chain = lookupSymbolChainWorker(sym, context, meaning); @@ -30799,6 +30799,10 @@ var ts; context.usedSymbolNames.set(name, true); }); } + ts.forEachEntry(symbolTable, function (symbol, name) { + var baseName = ts.unescapeLeadingUnderscores(name); + void getInternalSymbolName(symbol, baseName); + }); var addingDeclare = !bundled; var exportEquals = symbolTable.get("export="); if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152) { @@ -30951,7 +30955,11 @@ var ts; isPrivate = true; } var modifierFlags = (!isPrivate ? 1 : 0) | (isDefault && !needsPostExportDefault ? 512 : 0); - if (symbol.flags & 16) { + var isConstMergedWithNS = symbol.flags & 1536 && + symbol.flags & (2 | 1 | 4) && + symbol.escapedName !== "export="; + var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol); + if (symbol.flags & 16 || isConstMergedWithNSPrintableAsSignatureMerge) { serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } if (symbol.flags & 524288) { @@ -30960,7 +30968,8 @@ var ts; if (symbol.flags & (2 | 1 | 4) && symbol.escapedName !== "export=" && !(symbol.flags & 4194304) - && !(symbol.flags & 32)) { + && !(symbol.flags & 32) + && !isConstMergedWithNSPrintableAsSignatureMerge) { serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags); } if (symbol.flags & 384) { @@ -30974,7 +30983,7 @@ var ts; serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } } - if (symbol.flags & (512 | 1024)) { + if ((symbol.flags & (512 | 1024) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) { serializeModule(symbol, symbolName, modifierFlags); } if (symbol.flags & 64) { @@ -31000,7 +31009,10 @@ var ts; } } function includePrivateSymbol(symbol) { + if (ts.some(symbol.declarations, ts.isParameterDeclaration)) + return; ts.Debug.assertDefined(deferredPrivates); + getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); deferredPrivates.set("" + getSymbolId(symbol), symbol); } function isExportingScope(enclosingDeclaration) { @@ -31053,22 +31065,31 @@ var ts; var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.createHeritageClause(89, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b); }))]; addResult(ts.createInterfaceDeclaration(undefined, undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } + function getNamespaceMembersForSerialization(symbol) { + return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304) || (p.escapedName === "prototype")); }); + } + function isTypeOnlyNamespace(symbol) { + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551); }); + } function serializeModule(symbol, symbolName, modifierFlags) { - var members = !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304) || (p.escapedName === "prototype")); }); + var members = getNamespaceMembersForSerialization(symbol); var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; }); var realMembers = locationMap.get("real") || ts.emptyArray; var mergedMembers = locationMap.get("merged") || ts.emptyArray; if (ts.length(realMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 | 67108864))); } if (ts.length(mergedMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - ts.forEach(mergedMembers, includePrivateSymbol); var nsBody = ts.createModuleBlock([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export="; }), function (s) { var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); - return ts.createExportSpecifier(name === localName ? undefined : localName, name); + var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, true); + includePrivateSymbol(target || s); + var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; + return ts.createExportSpecifier(name === targetName ? undefined : targetName, name); })))]); addResult(ts.createModuleDeclaration(undefined, undefined, ts.createIdentifier(localName), nsBody, 16), 0); } @@ -31200,7 +31221,7 @@ var ts; addResult(ts.createNamespaceExportDeclaration(ts.idText(node.name)), 0); break; case 254: - addResult(ts.createImportDeclaration(undefined, undefined, ts.createImportClause(ts.createIdentifier(localName), undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0); + addResult(ts.createImportDeclaration(undefined, undefined, ts.createImportClause(ts.createIdentifier(localName), undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0); break; case 255: addResult(ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(localName))), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0); @@ -31208,7 +31229,7 @@ var ts; case 257: addResult(ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamedImports([ ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName)) - ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0); + ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0); break; case 261: var specifier = node.parent.parent.moduleSpecifier; @@ -31218,6 +31239,7 @@ var ts; serializeMaybeAliasAssignment(symbol); break; case 208: + case 193: if (symbol.escapedName === "default" || symbol.escapedName === "export=") { serializeMaybeAliasAssignment(symbol); } @@ -31225,8 +31247,6 @@ var ts; serializeExportSpecifier(localName, targetName); } break; - case 193: - break; default: return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!"); } @@ -31244,7 +31264,7 @@ var ts; var isExportAssignment = isExportEquals || isDefault; var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol); var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, true); - if (target) { + if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) { var expr = isExportAssignment ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl); var first_1 = ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined; var referenced = first_1 && resolveEntityName(first_1, 67108863, true, true, enclosingDeclaration); @@ -31296,6 +31316,7 @@ var ts; return ts.getObjectFlags(typeToSerialize) & (16 | 32) && !getIndexInfoOfType(typeToSerialize, 0) && !getIndexInfoOfType(typeToSerialize, 1) && + !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0))) && !ts.length(getSignaturesOfType(typeToSerialize, 1)) && !getDeclarationWithTypeAnnotation(hostSymbol) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && @@ -31404,7 +31425,7 @@ var ts; return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = getFirstIdentifier(node); + var leftmost = ts.getFirstIdentifier(node); var sym = resolveEntityName(leftmost, 67108863, true, true); if (sym) { includePrivateSymbol(sym); @@ -31530,11 +31551,8 @@ var ts; return context.remappedSymbolNames.get("" + getSymbolId(symbol)); } } - if (input === "default") { - input = "_default"; - } - else if (input === "export=") { - input = "_exports"; + if (symbol) { + input = getNameCandidateWorker(symbol, input); } var i = 0; var original = input; @@ -31548,17 +31566,28 @@ var ts; } return input; } - function getInternalSymbolName(symbol, localName) { - if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) { - return context.remappedSymbolNames.get("" + getSymbolId(symbol)); - } + function getNameCandidateWorker(symbol, localName) { if (localName === "default" || localName === "__class" || localName === "__function") { var flags = context.flags; context.flags |= 16777216; var nameCandidate = getNameOfSymbolAsWritten(symbol, context); context.flags = flags; - localName = ts.isIdentifierText(nameCandidate, languageVersion) && !ts.isStringANonContextualKeyword(nameCandidate) ? nameCandidate : getUnusedName("_default", symbol); + localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate; } + if (localName === "default") { + localName = "_default"; + } + else if (localName === "export=") { + localName = "_exports"; + } + localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_"); + return localName; + } + function getInternalSymbolName(symbol, localName) { + if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) { + return context.remappedSymbolNames.get("" + getSymbolId(symbol)); + } + localName = getNameCandidateWorker(symbol, localName); context.remappedSymbolNames.set("" + getSymbolId(symbol), localName); return localName; } @@ -31793,7 +31822,7 @@ var ts; } if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); + var firstIdentifier = ts.getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 | 788968 | 1920, undefined, undefined, false); var id = importSymbol && "" + getSymbolId(importSymbol); if (importSymbol && !visited.has(id)) { @@ -31845,6 +31874,8 @@ var ts; return !!target.immediateBaseConstraint; case 6: return !!getSymbolLinks(target).resolvedJSDocType; + case 7: + return !!target.resolvedTypeArguments; } return ts.Debug.assertNever(propertyName); } @@ -31919,7 +31950,9 @@ var ts; } var stringIndexInfo = getIndexInfoOfType(source, 0); var numberIndexInfo = getIndexInfoOfType(source, 1); - return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + result.objectFlags |= 131072; + return result; } function getFlowTypeOfDestructuring(node, declaredType) { var reference = getSyntheticElementAccess(node); @@ -32258,23 +32291,23 @@ var ts; kind === 2 && symbol.escapedName === "export=") { var exportedType_1 = resolveStructuredTypeMembers(type); - var members_3 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_3); + var members_4 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_3.has(name)) { + if (members_4.has(name)) { var exportedMember = exportedType_1.members.get(name); var union = createSymbol(s.flags | exportedMember.flags, name); union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_3.set(name, union); + members_4.set(name, union); } else { - members_3.set(name, s); + members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384); return result; } @@ -32327,7 +32360,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 | 524288; + var objectFlags = 128 | 1048576; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -32439,14 +32472,10 @@ var ts; if (!declaration.statements.length) { return emptyObjectType; } - var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); - if (type_1.flags & 524288) { - return getRegularTypeOfObjectLiteral(type_1); - } - return type_1; + return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression))); } if (!pushTypeResolution(symbol, 0)) { - if (symbol.flags & 512) { + if (symbol.flags & 512 && !(symbol.flags & 67108864)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -32510,7 +32539,7 @@ var ts; return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol)); } if (!popTypeResolution()) { - if (symbol.flags & 512) { + if (symbol.flags & 512 && !(symbol.flags & 67108864)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -32589,7 +32618,9 @@ var ts; } else { ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -32634,11 +32665,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=")); - var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_2; + return type_1; } } var type = createObjectType(16, symbol); @@ -32807,6 +32838,7 @@ var ts; } function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 245); + ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { @@ -32831,7 +32863,7 @@ var ts; var signatures = getSignaturesOfType(type, 1); if (signatures.length === 1) { var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -33402,8 +33434,8 @@ var ts; var decl = _a[_i]; var members = ts.getMembersOfDeclaration(decl); if (members) { - for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { - var member = members_4[_b]; + for (var _b = 0, members_5 = members; _b < members_5.length; _b++) { + var member = members_5[_b]; if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { lateBindMember(symbol, earlySymbols, lateSymbols, member); } @@ -33520,8 +33552,8 @@ var ts; var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + var sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -33529,14 +33561,12 @@ var ts; sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; } function cloneSignature(sig) { - var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, undefined, undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, undefined, undefined, sig.minArgumentCount, sig.flags & 3); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -33548,13 +33578,25 @@ var ts; result.mapper = undefined; return result; } - function createOptionalCallSignature(signature) { + function getOptionalCallSignature(signature, callChainFlags) { + if ((signature.flags & 12) === callChainFlags) { + return signature; + } + if (!signature.optionalCallSignatureCache) { + signature.optionalCallSignatureCache = {}; + } + var key = callChainFlags === 4 ? "inner" : "outer"; + return signature.optionalCallSignatureCache[key] + || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags)); + } + function createOptionalCallSignature(signature, callChainFlags) { + ts.Debug.assert(callChainFlags === 4 || callChainFlags === 8, "An optional call signature can either be for an inner call chain or an outer call chain, but not both."); var result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= callChainFlags; return result; } function getExpandedParameters(sig) { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { var restIndex_1 = sig.parameters.length - 1; var restParameter = sig.parameters[restIndex_1]; var restType = getTypeOfSymbol(restParameter); @@ -33579,7 +33621,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, undefined, 0, false, false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, undefined, 0, 0)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJSFile(baseTypeNode); @@ -33726,9 +33768,7 @@ var ts; var params = combineUnionParameters(left, right); var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - var hasRestParam = left.hasRestParameter || right.hasRestParameter; - var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; - var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, undefined, undefined, minArgCount, hasRestParam, hasLiteralTypes); + var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, undefined, undefined, minArgCount, (left.flags | right.flags) & 3); result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); return result; } @@ -33883,7 +33923,7 @@ var ts; var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor")) : ts.emptyArray; if (symbol.flags & 16) { constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, undefined, sig.minArgumentCount, sig.flags & 3) : undefined; })); } if (!constructSignatures.length) { @@ -34325,8 +34365,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_3 = types_6[_i]; - var baseType = getBaseConstraint(type_3); + var type_2 = types_6[_i]; + var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } @@ -34706,7 +34746,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var flags = 0; var minArgumentCount = 0; var thisParameter = void 0; var hasThisParameter = false; @@ -34733,7 +34773,7 @@ var ts; parameters.push(paramSymbol); } if (type && type.kind === 186) { - hasLiteralTypes = true; + flags |= 2; } var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || param.initializer || param.questionToken || param.dotDotDotToken || @@ -34757,8 +34797,10 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, undefined, undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1; + } + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, undefined, undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -34891,8 +34933,11 @@ var ts; signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, true); + if (signature.flags & 4) { + type = addOptionalTypeMarker(type); + } + else if (signature.flags & 8) { + type = getOptionalType(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -34948,7 +34993,7 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, 1); @@ -35137,7 +35182,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 1835008; + return result & 3670016; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -35171,13 +35216,25 @@ var ts; return type; } function getTypeArguments(type) { + var _a, _b; if (!type.resolvedTypeArguments) { + if (!pushTypeResolution(type, 7)) { + return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray; + } var node = type.node; var typeArguments = !node ? ts.emptyArray : node.kind === 168 ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : node.kind === 173 ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode); - type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + if (popTypeResolution()) { + type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + } + else { + type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray; + error(type.node || currentNode, type.target.symbol + ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves + : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol)); + } } return type.resolvedTypeArguments; } @@ -35278,7 +35335,7 @@ var ts; errorType; } if (symbol.flags & 111551 && isJSDocTypeReference(node)) { - var jsdocType = getTypeFromJSAlias(node, symbol); + var jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -35289,14 +35346,25 @@ var ts; } return errorType; } - function getTypeFromJSAlias(node, symbol) { + function getTypeFromJSDocValueReference(node, symbol) { var valueType = getTypeOfSymbol(symbol); - var typeType = valueType.symbol && - valueType.symbol !== symbol && - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + var typeType = valueType; + if (symbol.valueDeclaration) { + var decl = ts.getRootDeclaration(symbol.valueDeclaration); + var isRequireAlias = false; + if (ts.isVariableDeclaration(decl) && decl.initializer) { + var expr = decl.initializer; + while (ts.isPropertyAccessExpression(expr)) { + expr = expr.expression; + } + isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, true) && !!valueType.symbol; + } + var isImportTypeWithQualifier = node.kind === 187 && node.qualifier; + if (isRequireAlias || isImportTypeWithQualifier) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable, substitute) { if (substitute.flags & 3 || substitute === typeVariable) { @@ -35703,7 +35771,7 @@ var ts; if (type === wildcardType) includes |= 4194304; if (!strictNullChecks && flags & 98304) { - if (!(ts.getObjectFlags(type) & 262144)) + if (!(ts.getObjectFlags(type) & 524288)) includes |= 2097152; } else { @@ -35816,7 +35884,7 @@ var ts; neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 ? 0 : 131072, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 66994211 ? 0 : 262144, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -35947,14 +36015,14 @@ var ts; } function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 131072); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144); }); if (index < 0) { return false; } var i = index + 1; while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 131072) { + if (ts.getObjectFlags(t) & 262144) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -35978,7 +36046,7 @@ var ts; } } } - types[index] = getUnionTypeFromSortedList(result, 131072); + types[index] = getUnionTypeFromSortedList(result, 262144); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -36682,7 +36750,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host)) { + while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 137) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -36774,7 +36842,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 | 524288 | 1024 | objectFlags; + spread.objectFlags |= 128 | 1048576 | 1024 | objectFlags; return spread; } function isSpreadableProperty(prop) { @@ -37065,7 +37133,7 @@ var ts; tp.mapper = mapper; } } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, undefined, signature.minArgumentCount, signature.flags & 3); result.target = signature; result.mapper = mapper; return result; @@ -37846,14 +37914,14 @@ var ts; return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, 0, ignoreReturnTypes, false, undefined, undefined, compareTypesAssignable) !== 0; + return compareSignaturesRelated(source, target, 0, ignoreReturnTypes, false, undefined, undefined, compareTypesAssignable, undefined) !== 0; } function isAnySignature(s) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } - function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) { if (source === target) { return -1; } @@ -37871,6 +37939,9 @@ var ts; var sourceCount = getParameterCount(source); var sourceRestType = getNonArrayRestType(source); var targetRestType = getNonArrayRestType(target); + if (sourceRestType || targetRestType) { + void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers); + } if (sourceRestType && targetRestType && sourceCount !== targetCount) { return 0; } @@ -37903,7 +37974,7 @@ var ts; var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && (getFalsyFlags(sourceType) & 98304) === (getFalsyFlags(targetType) & 98304); var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 : 1, false, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) : + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 : 1, false, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { @@ -37915,13 +37986,13 @@ var ts; } if (!ignoreReturnTypes) { var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType - : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(target.declaration.symbol) + : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol)) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType - : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(source.declaration.symbol) + : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol)) : getReturnTypeOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -38100,7 +38171,7 @@ var ts; return true; } if (source.flags & 524288 && target.flags & 524288) { - var related = relation.get(getRelationKey(source, target, relation)); + var related = relation.get(getRelationKey(source, target, false, relation)); if (related !== undefined) { return !!(related & 1); } @@ -38417,7 +38488,7 @@ var ts; var isIntersectionConstituent = !!isApparentIntersectionConstituent; if (source.flags & 1048576) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068), isIntersectionConstituent) : + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068)) : eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068)); } else { @@ -38440,7 +38511,7 @@ var ts; } } else if (source.flags & 2097152) { - result = someTypeRelatedToType(source, target, false, true); + result = someTypeRelatedToType(source, target, false); } if (!result && (source.flags & 66846720 || target.flags & 66846720)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { @@ -38528,7 +38599,7 @@ var ts; if (!errorNode) return { value: ts.Debug.fail() }; if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { - if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration)) { + if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) { errorNode = prop.valueDeclaration.name; } reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget)); @@ -38536,7 +38607,7 @@ var ts; else { var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; - if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) { var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; @@ -38691,14 +38762,14 @@ var ts; } return result; } - function someTypeRelatedToType(source, target, reportErrors, isIntersectionConstituent) { + function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; if (source.flags & 1048576 && containsType(sourceTypes, target)) { return -1; } var len = sourceTypes.length; for (var i = 0; i < len; i++) { - var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, undefined, isIntersectionConstituent); + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { return related; } @@ -38767,7 +38838,7 @@ var ts; if (overflow) { return 0; } - var id = getRelationKey(source, target, relation); + var id = getRelationKey(source, target, isIntersectionConstituent, relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 && !(entry & 4)) { @@ -39530,7 +39601,7 @@ var ts; return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); }; } function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0, false, reportErrors, reportError, incompatibleReporter, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0, false, reportErrors, reportError, incompatibleReporter, isRelatedTo, reportUnreliableMarkers); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -39781,17 +39852,18 @@ var ts; } return result; } - function getRelationKey(source, target, relation) { + function getRelationKey(source, target, isIntersectionConstituent, relation) { if (relation === identityRelation && source.id > target.id) { var temp = source; source = target; target = temp; } + var intersection = isIntersectionConstituent ? "&" : ""; if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { var typeParameters = []; - return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + intersection; } - return source.id + "," + target.id; + return source.id + "," + target.id + intersection; } function forEachProperty(prop, callback) { if (ts.getCheckFlags(prop) & 6) { @@ -39825,7 +39897,7 @@ var ts; !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5 && type.flags & 524288) { + if (depth >= 5 && type.flags & 524288 && !isObjectOrArrayLiteralType(type)) { var symbol = type.symbol; if (symbol) { var count = 0; @@ -40164,33 +40236,19 @@ var ts; function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type) { + return type !== optionalType; + } function removeOptionalTypeMarker(type) { - return strictNullChecks ? filterType(type, function (t) { return t !== optionalType; }) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } - function propagateOptionalTypeMarker(type, wasOptional) { - return wasOptional ? addOptionalTypeMarker(type) : type; + function propagateOptionalTypeMarker(type, node, wasOptional) { + return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional, type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - function checkOptionalExpression(parent, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var isOptional = false; - var type = checkExpression(expression); - if (ts.isOptionalChain(parent)) { - if (parent.questionDotToken) { - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - var nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType, expression) { + return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } function isCoercibleUnderDoubleEquals(source, target) { return ((source.flags & (8 | 4 | 512)) !== 0) @@ -40313,14 +40371,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 | 1048576)); + result.objectFlags |= (ts.getObjectFlags(type) & (16384 | 2097152)); return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 786432) { + if (ts.getObjectFlags(type) & 1572864) { if (context === undefined && type.widened) { return type.widened; } @@ -40351,7 +40409,7 @@ var ts; } function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 262144) { + if (ts.getObjectFlags(type) & 524288) { if (type.flags & 1048576) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -40377,7 +40435,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) & 262144) { + if (ts.getObjectFlags(t) & 524288) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -40455,7 +40513,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 262144) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288) { if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); } @@ -40568,7 +40626,7 @@ var ts; return !!(type.flags & 63176704 || 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 || + objectFlags & (32 | 131072) || type.flags & 3145728 && !(type.flags & 1024) && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { @@ -40612,7 +40670,7 @@ var ts; return type; } function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 1048576) || + return !(ts.getObjectFlags(type) & 2097152) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }); } function createReverseMappedType(source, target, constraint) { @@ -40738,10 +40796,7 @@ var ts; } target = getUnionType(targets); if (sources.length === 0) { - var savePriority = priority; - priority |= 1; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, 1); return; } source = getUnionType(sources); @@ -40760,7 +40815,7 @@ var ts; target = getActualTypeVariable(target); } if (target.flags & 8650752) { - if (ts.getObjectFlags(source) & 1048576 || source === silentNeverType || (priority & 16 && (source === autoType || source === autoArrayType))) { + if (ts.getObjectFlags(source) & 2097152 || source === silentNeverType || (priority & 16 && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -40821,10 +40876,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4) && target.flags & 4194304) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - var savePriority = priority; - priority |= 32; - inferFromTypes(empty, target.type); - priority = savePriority; + inferWithPriority(empty, target.type, 32); contravariant = !contravariant; } else if (source.flags & 8388608 && target.flags & 8388608) { @@ -40865,6 +40917,12 @@ var ts; } } } + function inferWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -40930,6 +40988,18 @@ var ts; } return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types) { + var typeVariable; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var type = types_13[_i]; + var t = type.flags & 2097152 && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } function inferToMultipleTypes(source, targets, targetFlags) { var typeVariableCount = 0; if (targetFlags & 1048576) { @@ -40955,6 +41025,13 @@ var ts; } } } + if (typeVariableCount === 0) { + var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1); + } + return; + } if (typeVariableCount === 1 && !inferenceCircularity) { var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; }); if (unmatched.length) { @@ -40975,15 +41052,12 @@ var ts; } } if (targetFlags & 2097152 ? typeVariableCount === 1 : typeVariableCount > 0) { - var savePriority = priority; - priority |= 1; for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) { var t = targets_4[_b]; if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, 1); } } - priority = savePriority; } } function inferToMappedType(source, target, constraintType) { @@ -41000,20 +41074,15 @@ var ts; if (inference && !inference.isFixed) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - var savePriority = priority; - priority |= ts.getObjectFlags(source) & 1048576 ? - 4 : 2; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 ? + 4 : + 2); } } return true; } if (constraintType.flags & 262144) { - var savePriority = priority; - priority |= 8; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, 8); var extendedConstraint = getConstraintOfType(constraintType); if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) { return true; @@ -41108,7 +41177,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 1048576); + var skipParameters = !!(ts.getObjectFlags(source) & 2097152); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -41348,6 +41417,15 @@ var ts; } return false; } + function optionalChainContainsReference(source, target) { + while (ts.isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } function containsMatchingReferenceDiscriminant(source, target) { var name; return ts.isAccessExpression(target) && @@ -41457,8 +41535,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; result |= getTypeFacts(t); } return result; @@ -41809,8 +41887,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 131072)) { if (!(ts.getObjectFlags(t) & 256)) { return false; @@ -41878,9 +41956,18 @@ var ts; var links = getNodeLinks(node); var signature = links.effectsSignature; if (signature === undefined) { - var funcType = node.parent.kind === 225 ? getTypeOfDottedName(node.expression, undefined) : - node.expression.kind !== 101 ? checkOptionalExpression(node, node.expression).type : - undefined; + var funcType = void 0; + if (node.parent.kind === 225) { + funcType = getTypeOfDottedName(node.expression, undefined); + } + else if (node.expression.kind !== 101) { + if (ts.isOptionalChain(node)) { + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0); var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -41893,6 +41980,13 @@ var ts; return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072); } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 || predicate.kind === 3) { + return callExpression.arguments[predicate.parameterIndex]; + } + var invokedExpression = ts.skipParentheses(callExpression.expression); + return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined; + } function reportFlowControlError(node) { var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); var sourceFile = ts.getSourceFileOfNode(node); @@ -41908,6 +42002,11 @@ var ts; function isUnlockedReachableFlowNode(flow) { return !(flow.flags & 4096 && flow.lock.locked) && isReachableFlowNodeWorker(flow, false); } + function isFalseExpression(expr) { + var node = ts.skipParentheses(expr); + return node.kind === 90 || node.kind === 208 && (node.operatorToken.kind === 55 && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === 56 && isFalseExpression(node.left) && isFalseExpression(node.right)); + } function isReachableFlowNodeWorker(flow, noCacheCheck) { while (true) { if (flow === lastFlowNode) { @@ -41927,8 +42026,17 @@ var ts; } else if (flags & 512) { var signature = getEffectsSignature(flow.node); - if (signature && getReturnTypeOfSignature(signature).flags & 131072) { - return false; + if (signature) { + var predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3) { + var predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072) { + return false; + } } flow = flow.antecedent; } @@ -42128,6 +42236,9 @@ var ts; } function narrowTypeByAssertion(type, expr) { var node = ts.skipParentheses(expr); + if (node.kind === 90) { + return unreachableNeverType; + } if (node.kind === 208) { if (node.operatorToken.kind === 55) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); @@ -42146,7 +42257,7 @@ var ts; var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, true) : - predicate.kind === 3 ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === 3 && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -42209,17 +42320,24 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } else if (expr.kind === 203 && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 | 131072)); }); + } + else if (expr.kind === 203 && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 || t.flags & 128 && t.value === "undefined"); }); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -42227,11 +42345,16 @@ var ts; var antecedentTypes = []; var subtypeReduction = false; var seenIncomplete = false; + var bypassFlow; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; if (antecedent.flags & 4096 && antecedent.lock.locked) { continue; } + if (!bypassFlow && antecedent.flags & 128 && antecedent.clauseStart === antecedent.clauseEnd) { + bypassFlow = antecedent; + continue; + } var flowType = getTypeAtFlowNode(antecedent); var type = getTypeFromFlowType(flowType); if (type === declaredType && declaredType === initialType) { @@ -42245,6 +42368,22 @@ var ts; seenIncomplete = true; } } + if (bypassFlow) { + var flowType = getTypeAtFlowNode(bypassFlow); + var type = getTypeFromFlowType(flowType); + if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) { + if (type === declaredType && declaredType === initialType) { + return type; + } + antecedentTypes.push(type); + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + } return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 : 1), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { @@ -42323,6 +42462,9 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 : 8388608); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, 2097152); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 : 8388608); }); } @@ -42371,6 +42513,14 @@ var ts; if (isMatchingReference(reference, right_1)) { return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + } + else if (optionalChainContainsReference(right_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left_1, declaredType)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } @@ -42394,6 +42544,12 @@ var ts; } return type; } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + var effectiveTrue = operator === 34 || operator === 36 ? assumeTrue : !assumeTrue; + var doubleEquals = operator === 34 || operator === 35; + var valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? 262144 : 65536)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, 2097152) : type; + } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1) { return type; @@ -42440,16 +42596,19 @@ var ts; return type; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + if (operator === 35 || operator === 37) { + assumeTrue = !assumeTrue; + } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, 2097152); + } if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (operator === 35 || operator === 37) { - assumeTrue = !assumeTrue; - } if (type.flags & 1 && literal.text === "function") { return type; } @@ -42479,6 +42638,10 @@ var ts; return type; } } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { + var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152) : type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { @@ -42572,6 +42735,9 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, 2097152); + } if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) { return declaredType; } @@ -42626,36 +42792,25 @@ var ts; return type; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === 1 || predicate.kind === 3) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + var predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & 65536)) { + return getTypeWithFacts(type, 2097152); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (ts.isAccessExpression(invokedExpression) && predicate.type) { - var possibleReference = ts.skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } function narrowType(type, expr, assumeTrue) { - if (ts.isOptionalChainRoot(expr.parent) || + if (ts.isExpressionOfOptionalChainRoot(expr) || ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -42893,7 +43048,19 @@ var ts; } } else if (!assumeInitialized && !(getFalsyFlags(type) & 32768) && getFalsyFlags(flowType) & 32768) { - error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + var diag = error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + if (type.symbol && type.symbol.declarations.length === 1 && ts.isFunctionTypeNode(type.symbol.declarations[0])) { + var funcTypeNode = type.symbol.declarations[0]; + var returnType = getReturnTypeFromAnnotation(funcTypeNode); + if (returnType && returnType.flags & 1048576) { + var unionTypes_3 = funcTypeNode.type.types; + if (unionTypes_3 && unionTypes_3[unionTypes_3.length - 1].kind === 145) { + var parenedFuncType = ts.getMutableClone(funcTypeNode); + parenedFuncType.end = unionTypes_3[unionTypes_3.length - 2].end; + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(parenedFuncType, ts.Diagnostics.Did_you_mean_to_parenthesize_this_function_type)); + } + } + } return type; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; @@ -43505,16 +43672,20 @@ var ts; } return undefined; } - function getContextualTypeForArgument(callTarget, arg) { + function getContextualTypeForArgument(callTarget, arg, contextFlags) { var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + function getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags) { var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & 4 && signature.target) { + var baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { @@ -43813,7 +43984,7 @@ var ts; return stringType; } case 196: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case 198: case 216: return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); @@ -44004,8 +44175,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44088,7 +44259,7 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 | 524288; + literalType.objectFlags |= 65536 | 1048576; } return literalType; } @@ -44198,7 +44369,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 1835008; + objectFlags |= ts.getObjectFlags(type) & 3670016; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096) : @@ -44296,7 +44467,7 @@ 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 | 524288; + result.objectFlags |= objectFlags | 128 | 1048576; if (isJSObjectLiteral) { result.objectFlags |= 16384; } @@ -44376,7 +44547,7 @@ var ts; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 1835008; + objectFlags |= ts.getObjectFlags(exprType) & 3670016; var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -44444,7 +44615,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); - result.objectFlags |= objectFlags | 128 | 524288; + result.objectFlags |= objectFlags | 128 | 1048576; return result; } } @@ -44805,8 +44976,8 @@ var ts; function symbolHasNonMethodDeclaration(symbol) { return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192); }); } - function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304); @@ -44814,22 +44985,34 @@ var ts; function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + function reportObjectPossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 ? flags & 65536 ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 ? flags & 65536 ? + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + } + function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304; if (kind) { - error(node, kind & 32768 ? kind & 65536 ? - (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + reportError(node, kind); var t = getNonNullableType(type); return t.flags & (98304 | 131072) ? errorType : t; } return type; } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & 16384) { @@ -44838,10 +45021,16 @@ var ts; return nonNullType; } function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & 32 ? checkPropertyAccessChain(node) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + function checkPropertyAccessChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); } function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node) { while (node.parent.kind === 199) { @@ -44849,8 +45038,7 @@ var ts; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var _a = checkOptionalExpression(node, left), isOptional = _a.isOptional, leftType = _a.type; + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -44903,7 +45091,7 @@ var ts; } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { var assignmentKind = ts.getAssignmentTargetKind(node); @@ -45181,7 +45369,15 @@ var ts; return false; } function checkIndexedAccess(node) { - var _a = checkOptionalExpression(node, node.expression), isOptional = _a.isOptional, exprType = _a.type; + return node.flags & 32 ? checkElementAccessChain(node) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + function checkElementAccessChain(node) { + var exprType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType) { var objectType = ts.getAssignmentTargetKind(node) !== 0 || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -45197,7 +45393,7 @@ var ts; 2 | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 : 0) : 0; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -45253,7 +45449,7 @@ var ts; resolveUntypedCall(node); return unknownSignature; } - function reorderCandidates(signatures, result, isOptionalCall) { + function reorderCandidates(signatures, result, callChainFlags) { var lastParent; var lastSymbol; var cutoffIndex = 0; @@ -45279,7 +45475,7 @@ var ts; lastParent = parent; } lastSymbol = symbol; - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; cutoffIndex++; @@ -45287,7 +45483,7 @@ var ts; else { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature); } } function isSpreadArgument(arg) { @@ -45358,7 +45554,7 @@ var ts; function hasCorrectTypeArgumentArity(signature, typeArguments) { var numTypeParameters = ts.length(signature.typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - return !typeArguments || + return !ts.some(typeArguments) || (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); } function getSingleCallSignature(type) { @@ -45529,7 +45725,19 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType && thisType !== voidType && node.kind !== 196) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var thisArgumentType = void 0; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (ts.isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -45729,7 +45937,7 @@ var ts; 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.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_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 (min < argCount && argCount < max) { @@ -45783,7 +45991,7 @@ var ts; } return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } - function resolveCall(node, signatures, candidatesOutArray, checkMode, isOptionalCall, fallbackError) { + function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { var isTaggedTemplate = node.kind === 197; var isDecorator = node.kind === 156; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -45796,7 +46004,7 @@ var ts; } } var candidates = candidatesOutArray || []; - reorderCandidates(signatures, candidates, isOptionalCall); + reorderCandidates(signatures, candidates, callChainFlags); if (!candidates.length) { if (reportErrors) { diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); @@ -45909,7 +46117,7 @@ var ts; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (getSignatureApplicabilityError(node, args, candidate, relation, 0, false, undefined)) { @@ -45927,7 +46135,7 @@ var ts; var inferenceContext = void 0; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - if (typeArguments) { + if (ts.some(typeArguments)) { typeArgumentTypes = checkTypeArguments(candidate, typeArguments, false); if (!typeArgumentTypes) { candidateForTypeArgumentError = candidate; @@ -45988,29 +46196,30 @@ var ts; var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; var _loop_15 = function (i) { - var symbols = ts.mapDefined(candidates, function (_a) { - var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; - return hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : - i < parameters.length ? parameters[i] : undefined; - }); + var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined; }); ts.Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { _loop_15(i); } - var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); - var hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); + var flags = 0; + if (restParameterSymbols.length !== 0) { var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1; } - return createSignature(candidates[0].declaration, undefined, thisParameter, parameters, getIntersectionType(candidates.map(getReturnTypeOfSignature)), undefined, minArgumentCount, hasRestParameter, candidates.some(function (c) { return c.hasLiteralTypes; })); + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2; + } + return createSignature(candidates[0].declaration, undefined, thisParameter, parameters, getIntersectionType(candidates.map(getReturnTypeOfSignature)), undefined, minArgumentCount, flags); } function getNumNonRestParameters(signature) { var numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2)); @@ -46077,12 +46286,24 @@ var ts; var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, false); + return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0); } } return resolveUntypedCall(node); } - var _b = checkOptionalExpression(node, node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined), isOptional = _b.isOptional, funcType = _b.type; + var callChainFlags; + var funcType = checkExpression(node.expression); + if (ts.isCallChain(node)) { + var nonOptionalType = getOptionalExpressionType(funcType, node.expression); + callChainFlags = nonOptionalType === funcType ? 0 : + ts.isOutermostOptionalChain(node) ? 8 : + 4; + funcType = nonOptionalType; + } + else { + callChainFlags = 0; + } + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -46122,7 +46343,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, isOptional); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags); } function isGenericFunctionReturningFunction(signature) { return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature))); @@ -46162,11 +46383,11 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, false); + return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0); } var callSignatures = getSignaturesOfType(expressionType, 0); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, false); + var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0); if (!noImplicitAny) { if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); @@ -46248,8 +46469,8 @@ var ts; if (apparentType.flags & 1048576) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var constituent = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var constituent = types_17[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -46333,7 +46554,7 @@ var ts; invocationError(node.tag, apparentType, 0); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, false); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0); } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { @@ -46380,7 +46601,7 @@ var ts; invocationErrorRecovery(apparentType, 0, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, false, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0, headMessage); } function createSignatureForJSXIntrinsic(node, result) { var namespace = getJsxNamespaceAt(node); @@ -46390,7 +46611,7 @@ var ts; var declaration = ts.createFunctionTypeNode(undefined, [ts.createParameter(undefined, undefined, undefined, "props", undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, undefined) : ts.createKeywordTypeNode(124)); var parameterSymbol = createSymbol(1, "props"); parameterSymbol.type = result; - return createSignature(declaration, undefined, undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, undefined, 1, false, false); + return createSignature(declaration, undefined, undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, undefined, 1, 0); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -46412,12 +46633,12 @@ var ts; error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); return resolveErrorCall(node); } - return resolveCall(node, signatures, candidatesOutArray, checkMode, false); + return resolveCall(node, signatures, candidatesOutArray, checkMode, 0); } function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } @@ -46466,7 +46687,7 @@ var ts; return false; } function mergeJSSymbols(target, source) { - if (source && (ts.hasEntries(source.exports) || ts.hasEntries(source.members))) { + if (source) { var links = getSymbolLinks(source); if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) { var inferred = isTransientSymbol(target) ? target : cloneSymbol(target); @@ -46758,7 +46979,7 @@ var ts; return type; } function getParameterNameAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -46775,11 +46996,11 @@ var ts; return tryGetTypeAtPosition(signature, pos) || anyType; } function tryGetTypeAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[paramCount]); var index = pos - paramCount; if (!isTupleType(restType) || restType.target.hasRestElement || index < getTypeArguments(restType).length) { @@ -46811,7 +47032,7 @@ var ts; } function getParameterCount(signature) { var length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -46820,7 +47041,7 @@ var ts; return length; } function getMinArgumentCount(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { var minLength = restType.target.minLength; @@ -46832,14 +47053,14 @@ var ts; return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } return false; } function getEffectiveRestType(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -46856,7 +47077,7 @@ var ts; return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, inferenceContext) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -46885,7 +47106,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } } - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -46893,7 +47114,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { var contextualParameterType = getRestTypeAtPosition(context, len); @@ -47125,8 +47346,8 @@ var ts; var operandType = getTypeOfExpression(node.expression.expression); var witnesses = getSwitchClauseTypeOfWitnesses(node); var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, true); - var type_4 = getBaseConstraintOfType(operandType) || operandType; - return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072); + var type_3 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -47227,9 +47448,9 @@ var ts; return links.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false); + 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 |= 1048576; + returnOnlyType.objectFlags |= 2097152; return links.contextFreeType = returnOnlyType; } return anyFunctionType; @@ -47425,8 +47646,7 @@ var ts; var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); var func = ts.getContainingFunction(node); - if (func && func.kind !== 161) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2) === 0, "Enclosing function should never be an async function."); + if (func && func.kind !== 161 && (ts.getFunctionFlags(func) & 2) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -47522,8 +47742,8 @@ var ts; } if (type.flags & 3145728) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48098,24 +48318,9 @@ var ts; } return [effectiveLeft, effectiveRight]; } - function isYieldExpressionInClass(node) { - var current = node; - var parent = node.parent; - while (parent) { - if (ts.isFunctionLike(parent) && current === parent.body) { - return false; - } - else if (ts.isClassLike(current)) { - return true; - } - current = parent; - parent = parent.parent; - } - return false; - } function checkYieldExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 8192) || isYieldExpressionInClass(node)) { + if (!(node.flags & 8192)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -48404,13 +48609,25 @@ var ts; } } } + function getReturnTypeOfSingleNonGenericCallSignature(funcType) { + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) { + var funcType = checkExpression(expr.expression); + var nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType); + return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType); + } function getTypeOfExpression(node, cache) { var expr = ts.skipParentheses(node); if (ts.isCallExpression(expr) && expr.expression.kind !== 101 && !ts.isRequireCall(expr, true) && !isSymbolOrSymbolForCall(expr)) { - var _a = checkOptionalExpression(expr, expr.expression), isOptional = _a.isOptional, funcType = _a.type; - var signature = getSingleCallSignature(funcType); - if (signature && !signature.typeParameters) { - return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); + var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : + getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression)); + if (type) { + return type; } } else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) { @@ -48446,7 +48663,7 @@ var ts; (node.parent.kind === 194 && node.parent.expression === node) || ((node.kind === 75 || node.kind === 152) && isInRightSideOfImportOrExportAssignment(node) || (node.parent.kind === 171 && node.parent.exprName === node)) || - (node.parent.kind === 261 && (compilerOptions.preserveConstEnums || node.flags & 8388608)); + (node.parent.kind === 261); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -48637,7 +48854,7 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -49596,7 +49813,7 @@ var ts; if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { return; } - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); @@ -49646,7 +49863,7 @@ var ts; function markEntityNameOrEntityExpressionAsReference(typeName) { if (!typeName) return; - var rootName = getFirstIdentifier(typeName); + var rootName = ts.getFirstIdentifier(typeName); var meaning = (typeName.kind === 75 ? 788968 : 1920) | 2097152; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); if (rootSymbol @@ -49679,8 +49896,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var typeNode = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var typeNode = types_19[_i]; while (typeNode.kind === 181) { typeNode = typeNode.type; } @@ -51098,10 +51315,7 @@ var ts; firstDefaultClause = clause; } else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -51118,6 +51332,9 @@ var ts; } } ts.forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -51565,11 +51782,13 @@ var ts; || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { continue; } - if (basePropertyFlags !== 4 && derivedPropertyFlags === 4) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property; - } - else if (basePropertyFlags === 4 && derivedPropertyFlags !== 4) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor; + var overriddenInstanceProperty = basePropertyFlags !== 4 && derivedPropertyFlags === 4; + var overriddenInstanceAccessor = basePropertyFlags === 4 && derivedPropertyFlags !== 4; + if (overriddenInstanceProperty || overriddenInstanceAccessor) { + var errorMessage_1 = overriddenInstanceProperty ? + ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : + 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 { var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 158 && !d.initializer; }); @@ -51585,22 +51804,20 @@ var ts; || !ts.isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { - var errorMessage_1 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; - error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType)); + var errorMessage_2 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType)); } } - continue; } + continue; } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { + if (isPrototypeProperty(derived) || derived.flags & 4) { continue; } - else if (derived.flags & 98304) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + ts.Debug.assert(!!(derived.flags & 98304)); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & 98304) { @@ -52066,22 +52283,6 @@ var ts; break; } } - function getFirstIdentifier(node) { - switch (node.kind) { - case 75: - return node; - case 152: - do { - node = node.left; - } while (node.kind !== 75); - return node; - case 193: - do { - node = node.expression; - } while (node.kind !== 75); - return node; - } - } function getFirstNonModuleExportsIdentifier(node) { switch (node.kind) { case 75: @@ -52194,7 +52395,7 @@ var ts; var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 111551) { - var moduleName = getFirstIdentifier(node.moduleReference); + var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 | 1920).flags & 1920)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } @@ -52254,7 +52455,7 @@ var ts; if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; var symbol = resolveName(exportedName, exportedName.escapedText, 111551 | 788968 | 1920 | 2097152, undefined, undefined, true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -54328,10 +54529,10 @@ var ts; if (type.flags & 4 || type.flags & 8) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & 1048576 && allTypesAssignableToKind(type, 128, true)) { + if (type.flags & 1048576 && allTypesAssignableToKind(type, 384, true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -55133,7 +55334,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -55198,6 +55399,14 @@ var ts; case 2: return "nextType"; } } + function signatureHasRestParameter(s) { + return !!(s.flags & 1); + } + ts.signatureHasRestParameter = signatureHasRestParameter; + function signatureHasLiteralTypes(s) { + return !!(s.flags & 2); + } + ts.signatureHasLiteralTypes = signatureHasLiteralTypes; })(ts || (ts = {})); var ts; (function (ts) { @@ -56103,7 +56312,9 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - ts.Debug.assert(!(node.flags & 32), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } return node.expression !== expression || node.name !== name ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) @@ -56137,7 +56348,9 @@ var ts; } ts.createElementAccess = createElementAccess; function updateElementAccess(node, expression, argumentExpression) { - ts.Debug.assert(!(node.flags & 32), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -56171,7 +56384,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - ts.Debug.assert(!(node.flags & 32), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (ts.isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -56769,7 +56984,7 @@ var ts; var node = createSynthesizedNode(231); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -58923,7 +59138,7 @@ var ts; var conditionalPrecedence = ts.getOperatorPrecedence(209, 57); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1) { return ts.createParen(condition); } return condition; @@ -59369,6 +59584,12 @@ var ts; } ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement); + ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element."); + return propertyName; + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { case 190: if (bindingElement.propertyName) { @@ -59395,9 +59616,8 @@ var ts; ? target.expression : target; } - ts.Debug.fail("Invalid property name for binding element."); } - ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; function isStringOrNumericLiteral(node) { var kind = node.kind; return kind === 10 @@ -61195,7 +61415,8 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node)) { value = ensureIdentifier(flattenContext, value, false, location); } else if (needsValue) { @@ -61248,6 +61469,17 @@ var ts; } return false; } + function bindingOrAssignmentElementContainsNonLiteralComputedName(element) { + var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element); + if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) { + return true; + } + var target = ts.getTargetOfBindingOrAssignmentElement(element); + return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target); + } + function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) { + return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName); + } function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { if (hoistTempVariables === void 0) { hoistTempVariables = false; } var pendingExpressions; @@ -61267,7 +61499,8 @@ var ts; }; if (ts.isVariableDeclaration(node)) { var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); - if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node))) { initializer = ensureIdentifier(flattenContext, initializer, false, initializer); node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); } @@ -62070,8 +62303,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { - var member = members_5[_i]; + for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { + var member = members_6[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -62337,8 +62570,8 @@ var ts; } function serializeTypeList(types) { var serializedUnion; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 181) { typeNode = typeNode.type; } @@ -62721,7 +62954,11 @@ var ts; } } } - function shouldEmitModuleDeclaration(node) { + function shouldEmitModuleDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration); + if (!node) { + return true; + } return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } function hasNamespaceQualifiedExportName(node) { @@ -63258,7 +63495,7 @@ var ts; } function visitPropertyDeclaration(node) { ts.Debug.assert(!ts.some(node.decorators)); - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -64681,7 +64918,7 @@ var ts; } return ts.updateParen(node, expression); } - function visitNonOptionalPropertyAccessExpression(node, captureThisArg) { + function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg) { if (ts.isOptionalChain(node)) { return visitOptionalExpression(node, captureThisArg); } @@ -64689,24 +64926,17 @@ var ts; ts.Debug.assertNotNode(expression, ts.isSyntheticReference); var thisArg; if (captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - expression = ts.createParen(ts.createAssignment(thisArg, expression)); + if (shouldCaptureInTempVariable(expression)) { + thisArg = ts.createTempVariable(hoistVariableDeclaration); + expression = ts.createAssignment(thisArg, expression); + } + else { + thisArg = expression; + } } - expression = ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)); - return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression; - } - function visitNonOptionalElementAccessExpression(node, captureThisArg) { - if (ts.isOptionalChain(node)) { - return visitOptionalExpression(node, captureThisArg); - } - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - ts.Debug.assertNotNode(expression, ts.isSyntheticReference); - var thisArg; - if (captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - expression = ts.createParen(ts.createAssignment(thisArg, expression)); - } - expression = ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); + expression = node.kind === 193 + ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) + : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression; } function visitNonOptionalCallExpression(node, captureThisArg) { @@ -64718,8 +64948,8 @@ var ts; function visitNonOptionalExpression(node, captureThisArg) { switch (node.kind) { case 199: return visitNonOptionalParenthesizedExpression(node, captureThisArg); - case 193: return visitNonOptionalPropertyAccessExpression(node, captureThisArg); - case 194: return visitNonOptionalElementAccessExpression(node, captureThisArg); + case 193: + case 194: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg); case 195: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } @@ -64727,31 +64957,36 @@ var ts; function visitOptionalExpression(node, captureThisArg) { var _a = flattenChain(node), expression = _a.expression, chain = _a.chain; var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0])); - var temp = ts.createTempVariable(hoistVariableDeclaration); var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined; var leftExpression = ts.isSyntheticReference(left) ? left.expression : left; - var rightExpression = temp; + var capturedLeft = leftExpression; + if (shouldCaptureInTempVariable(leftExpression)) { + capturedLeft = ts.createTempVariable(hoistVariableDeclaration); + leftExpression = ts.createAssignment(capturedLeft, leftExpression); + } + var rightExpression = capturedLeft; var thisArg; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { case 193: - if (i === chain.length - 1 && captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - rightExpression = ts.createParen(ts.createAssignment(thisArg, rightExpression)); - } - rightExpression = ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)); - break; case 194: if (i === chain.length - 1 && captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - rightExpression = ts.createParen(ts.createAssignment(thisArg, rightExpression)); + if (shouldCaptureInTempVariable(rightExpression)) { + thisArg = ts.createTempVariable(hoistVariableDeclaration); + rightExpression = ts.createAssignment(thisArg, rightExpression); + } + else { + thisArg = rightExpression; + } } - rightExpression = ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); + rightExpression = segment.kind === 193 + ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) + : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; case 195: if (i === 0 && leftThisArg) { - rightExpression = ts.createFunctionCall(rightExpression, leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); + rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 101 ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } else { rightExpression = ts.createCall(rightExpression, undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); @@ -64760,22 +64995,25 @@ var ts; } ts.setOriginalNode(rightExpression, segment); } - var target = ts.createConditional(ts.createLogicalOr(ts.createStrictEquality(ts.createAssignment(temp, leftExpression), ts.createNull()), ts.createStrictEquality(temp, ts.createVoidZero())), ts.createVoidZero(), rightExpression); + var target = ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, true), ts.createVoidZero(), rightExpression); return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target; } - function createNotNullCondition(node) { - return ts.createBinary(ts.createBinary(node, ts.createToken(37), ts.createNull()), ts.createToken(55), ts.createBinary(node, ts.createToken(37), ts.createVoidZero())); + function createNotNullCondition(left, right, invert) { + return ts.createBinary(ts.createBinary(left, ts.createToken(invert ? 36 : 37), ts.createNull()), ts.createToken(invert ? 56 : 55), ts.createBinary(right, ts.createToken(invert ? 36 : 37), ts.createVoidZero())); } function transformNullishCoalescingExpression(node) { - var expressions = []; var left = ts.visitNode(node.left, visitor, ts.isExpression); - if (!ts.isIdentifier(left)) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - expressions.push(ts.createAssignment(temp, left)); - left = temp; + var right = left; + if (shouldCaptureInTempVariable(left)) { + right = ts.createTempVariable(hoistVariableDeclaration); + left = ts.createAssignment(right, left); } - expressions.push(ts.createParen(ts.createConditional(createNotNullCondition(left), left, ts.visitNode(node.right, visitor, ts.isExpression)))); - return ts.inlineExpressions(expressions); + return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression)); + } + function shouldCaptureInTempVariable(expression) { + return !ts.isIdentifier(expression) && + expression.kind !== 103 && + expression.kind !== 101; } } ts.transformESNext = transformESNext; @@ -71496,6 +71734,7 @@ var ts; var combinedStatements; if (ts.isSourceFileJS(currentSourceFile)) { combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); } else { @@ -73037,7 +73276,11 @@ var ts; bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) + return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) + emitSkipped = true; return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -75598,8 +75841,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference", data: directive.fileName }); writeLine(); } - for (var _d = 0, types_20 = types; _d < types_20.length; _d++) { - var directive = types_20[_d]; + for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { + var directive = types_21[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -77265,26 +77508,31 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (system.directoryExists(directoryPath)) { + if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } return false; } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - if (compilerHost.createDirectory) { - compilerHost.createDirectory(directoryPath); - } - else { - system.createDirectory(directoryPath); + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); } } } var outputFingerprints; - function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + function writeFileWorker(fileName, data, writeByteOrderMark) { + if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) { + system.writeFile(fileName, data, writeByteOrderMark); + return; + } if (!outputFingerprints) { outputFingerprints = ts.createMap(); } @@ -77307,25 +77555,6 @@ var ts; mtime: mtimeAfter }); } - function writeFile(fileName, data, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { - writeFileIfUpdated(fileName, data, writeByteOrderMark); - } - else { - system.writeFile(fileName, data, writeByteOrderMark); - } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -78799,9 +79028,16 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - if (fail) - fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + var canonicalFileName_1 = host.getCanonicalFileName(fileName); + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) { + if (fail) { + if (ts.hasJSFileExtension(canonicalFileName_1)) { + fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName); + } + else { + fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + } + } return undefined; } var sourceFile = getSourceFile(fileName); @@ -78815,7 +79051,7 @@ var ts; fail(ts.Diagnostics.File_0_not_found, fileName); } } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) { fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); } } @@ -78870,6 +79106,15 @@ var ts; function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) { if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(fileName); + if (!source && + host.realpath && + options.preserveSymlinks && + ts.isDeclarationFileName(fileName) && + ts.stringContains(fileName, ts.nodeModulesPathPart)) { + var realPath = host.realpath(fileName); + if (realPath !== fileName) + source = getSourceOfProjectReferenceRedirect(realPath); + } if (source) { var file_1 = ts.isString(source) ? findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) : @@ -79347,9 +79592,6 @@ var ts; else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && ts.isIncrementalCompilation(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } verifyProjectReferences(); if (options.composite) { var rootPaths = ts.arrayToSet(rootNames, toPath); @@ -80230,6 +80472,7 @@ var ts; ts.Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = ts.createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -80810,7 +81053,7 @@ var ts; } var state = { fileInfos: fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), @@ -80846,33 +81089,6 @@ var ts; } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; - function convertFromReusableCompilerOptions(options, toAbsolutePath) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - function convertFromReusableCompilerOptionValue(option, value, toAbsolutePath) { - if (option) { - if (option.type === "list") { - var values = value; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value); - } - } - return value; - } function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -81497,7 +81713,7 @@ var ts; function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { return { relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 : 1, - ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? + ending: ts.hasJSFileExtension(oldImportSpecifier) ? 2 : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 : 0, }; @@ -81579,7 +81795,7 @@ var ts; var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } function numberOfDirectorySeparators(str) { @@ -81706,8 +81922,11 @@ var ts; } } var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); - if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); + var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { return undefined; + } var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; @@ -81901,7 +82120,7 @@ var ts; ts.createWatchStatusReporter = createWatchStatusReporter; function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; return result; @@ -81925,7 +82144,7 @@ var ts; } ts.getErrorSummaryText = getErrorSummaryText; function listFiles(program, writeFileName) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { ts.forEach(program.getSourceFiles(), function (file) { writeFileName(file.fileName); }); @@ -81933,17 +82152,22 @@ var ts; } ts.listFiles = listFiles; function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics(undefined, cancellationToken)); if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - ts.addRange(diagnostics, program.getSemanticDiagnostics(undefined, cancellationToken)); + if (!isListFilesOnly) { + ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getSemanticDiagnostics(undefined, cancellationToken)); + } } } - var emitResult = program.emit(undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + var emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: ts.emptyArray } + : program.emit(undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics; ts.addRange(diagnostics, emitDiagnostics); ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); @@ -82034,19 +82258,10 @@ var ts; createHash: ts.maybeBind(host, host.createHash), readDirectory: ts.maybeBind(host, host.readDirectory), }; - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - if (host.createDirectory) - host.createDirectory(directoryPath); - } - } function writeFile(fileName, text, writeByteOrderMark, onError) { try { ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); + ts.writeFileEnsuringDirectories(fileName, text, writeByteOrderMark, function (path, data, writeByteOrderMark) { return host.writeFile(path, data, writeByteOrderMark); }, function (path) { return host.createDirectory(path); }, function (path) { return host.directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -83672,30 +83887,25 @@ var ts; setupInitialBuild(state, cancellationToken); var reportQueue = true; var successfulProjects = 0; - var errorProjects = 0; while (true) { var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; - } } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ts.ExitStatus.DiagnosticsPresent_OutputsGenerated : - ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : - ts.ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); }) + ? ts.ExitStatus.Success + : successfulProjects + ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated + : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); @@ -83703,7 +83913,7 @@ var ts; return ts.ExitStatus.InvalidProject_OutputsSkipped; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped; } var options = state.options, host = state.host; var filesToDelete = options.dry ? [] : undefined; @@ -83990,18 +84200,17 @@ var ts; }); return count; } - var reportDiagnostic = ts.createDiagnosticReporter(ts.sys); - function updateReportDiagnostic(options) { - if (shouldBePretty(options)) { - reportDiagnostic = ts.createDiagnosticReporter(ts.sys, /*pretty*/ true); - } + function updateReportDiagnostic(sys, existing, options) { + return shouldBePretty(sys, options) ? + ts.createDiagnosticReporter(sys, /*pretty*/ true) : + existing; } - function defaultIsPretty() { - return !!ts.sys.writeOutputIsTTY && ts.sys.writeOutputIsTTY(); + function defaultIsPretty(sys) { + return !!sys.writeOutputIsTTY && sys.writeOutputIsTTY(); } - function shouldBePretty(options) { + function shouldBePretty(sys, options) { if (!options || typeof options.pretty === "undefined") { - return defaultIsPretty(); + return defaultIsPretty(sys); } return options.pretty; } @@ -84023,258 +84232,395 @@ var ts; ts.sort(ts.optionDeclarations, function (a, b) { return ts.compareStringsCaseInsensitive(a.name, b.name); }) : ts.filter(ts.optionDeclarations.slice(), function (v) { return !!v.showInSimplifiedHelpView; }); } - function executeCommandLineWorker(commandLine) { + function printVersion(sys) { + sys.write(ts.getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + sys.newLine); + } + function printHelp(sys, optionsList, syntaxPrefix) { + if (syntaxPrefix === void 0) { syntaxPrefix = ""; } + var output = []; + // We want to align our "syntax" and "examples" commands to a certain margin. + var syntaxLength = ts.getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; + var examplesLength = ts.getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; + var marginLength = Math.max(syntaxLength, examplesLength); + // Build up the syntactic skeleton. + var syntax = makePadding(marginLength - syntaxLength); + syntax += "tsc " + syntaxPrefix + "[" + ts.getDiagnosticText(ts.Diagnostics.options) + "] [" + ts.getDiagnosticText(ts.Diagnostics.file) + "...]"; + output.push(ts.getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); + output.push(sys.newLine + sys.newLine); + // Build up the list of examples. + var padding = makePadding(marginLength); + output.push(ts.getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine); + output.push(padding + "tsc --outFile file.js file.ts" + sys.newLine); + output.push(padding + "tsc @args.txt" + sys.newLine); + output.push(padding + "tsc --build tsconfig.json" + sys.newLine); + output.push(sys.newLine); + output.push(ts.getDiagnosticText(ts.Diagnostics.Options_Colon) + sys.newLine); + // We want our descriptions to align at the same column in our output, + // so we keep track of the longest option usage string. + marginLength = 0; + var usageColumn = []; // Things like "-d, --declaration" go in here. + var descriptionColumn = []; + var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind + for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { + var option = optionsList_1[_i]; + // If an option lacks a description, + // it is not officially supported. + if (!option.description) { + continue; + } + var usageText_1 = " "; + if (option.shortName) { + usageText_1 += "-" + option.shortName; + usageText_1 += getParamType(option); + usageText_1 += ", "; + } + usageText_1 += "--" + option.name; + usageText_1 += getParamType(option); + usageColumn.push(usageText_1); + var description = void 0; + if (option.name === "lib") { + description = ts.getDiagnosticText(option.description); + var element = option.element; + var typeMap = element.type; + optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); + } + else { + description = ts.getDiagnosticText(option.description); + } + descriptionColumn.push(description); + // Set the new margin for the description column if necessary. + marginLength = Math.max(usageText_1.length, marginLength); + } + // Special case that can't fit in the loop. + var usageText = " @<" + ts.getDiagnosticText(ts.Diagnostics.file) + ">"; + usageColumn.push(usageText); + descriptionColumn.push(ts.getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); + marginLength = Math.max(usageText.length, marginLength); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < usageColumn.length; i++) { + var usage = usageColumn[i]; + var description = descriptionColumn[i]; + var kindsList = optionsDescriptionMap.get(description); + output.push(usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine); + if (kindsList) { + output.push(makePadding(marginLength + 4)); + for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { + var kind = kindsList_1[_a]; + output.push(kind + " "); + } + output.push(sys.newLine); + } + } + for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { + var line = output_1[_b]; + sys.write(line); + } + return; + function getParamType(option) { + if (option.paramType !== undefined) { + return " " + ts.getDiagnosticText(option.paramType); + } + return ""; + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + } + function executeCommandLineWorker(sys, cb, commandLine) { + var reportDiagnostic = ts.createDiagnosticReporter(sys); if (commandLine.options.build) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Option_build_must_be_the_first_command_line_argument)); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } // Configuration file name (if any) var configFileName; if (commandLine.options.locale) { - ts.validateLocaleAndSetLanguage(commandLine.options.locale, ts.sys, commandLine.errors); + ts.validateLocaleAndSetLanguage(commandLine.options.locale, sys, commandLine.errors); } // If there are any errors due to command line parsing and/or // setting up localization, report them and quit. if (commandLine.errors.length > 0) { commandLine.errors.forEach(reportDiagnostic); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (commandLine.options.init) { - writeConfigFile(commandLine.options, commandLine.fileNames); - return ts.sys.exit(ts.ExitStatus.Success); + writeConfigFile(sys, reportDiagnostic, commandLine.options, commandLine.fileNames); + return sys.exit(ts.ExitStatus.Success); } if (commandLine.options.version) { - ts.printVersion(); - return ts.sys.exit(ts.ExitStatus.Success); + printVersion(sys); + return sys.exit(ts.ExitStatus.Success); } if (commandLine.options.help || commandLine.options.all) { - ts.printVersion(); - ts.printHelp(getOptionsForHelp(commandLine)); - return ts.sys.exit(ts.ExitStatus.Success); + printVersion(sys); + printHelp(sys, getOptionsForHelp(commandLine)); + return sys.exit(ts.ExitStatus.Success); + } + if (commandLine.options.watch && commandLine.options.listFilesOnly) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "listFilesOnly")); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (commandLine.options.project) { if (commandLine.fileNames.length !== 0) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line)); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } var fileOrDirectory = ts.normalizePath(commandLine.options.project); - if (!fileOrDirectory /* current directory "." */ || ts.sys.directoryExists(fileOrDirectory)) { + if (!fileOrDirectory /* current directory "." */ || sys.directoryExists(fileOrDirectory)) { configFileName = ts.combinePaths(fileOrDirectory, "tsconfig.json"); - if (!ts.sys.fileExists(configFileName)) { + if (!sys.fileExists(configFileName)) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project)); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } } else { configFileName = fileOrDirectory; - if (!ts.sys.fileExists(configFileName)) { + if (!sys.fileExists(configFileName)) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project)); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } } } else if (commandLine.fileNames.length === 0) { - var searchPath = ts.normalizePath(ts.sys.getCurrentDirectory()); - configFileName = ts.findConfigFile(searchPath, ts.sys.fileExists); + var searchPath = ts.normalizePath(sys.getCurrentDirectory()); + configFileName = ts.findConfigFile(searchPath, sys.fileExists); } if (commandLine.fileNames.length === 0 && !configFileName) { - ts.printVersion(); - ts.printHelp(getOptionsForHelp(commandLine)); - return ts.sys.exit(ts.ExitStatus.Success); + printVersion(sys); + printHelp(sys, getOptionsForHelp(commandLine)); + return sys.exit(ts.ExitStatus.Success); } - var commandLineOptions = commandLine.options; + var currentDirectory = sys.getCurrentDirectory(); + var commandLineOptions = ts.convertToOptionsWithAbsolutePaths(commandLine.options, function (fileName) { return ts.getNormalizedAbsolutePath(fileName, currentDirectory); }); if (configFileName) { - var configParseResult = ts.parseConfigFileWithSystem(configFileName, commandLineOptions, ts.sys, reportDiagnostic); // TODO: GH#18217 + var configParseResult = ts.parseConfigFileWithSystem(configFileName, commandLineOptions, sys, reportDiagnostic); // TODO: GH#18217 if (commandLineOptions.showConfig) { if (configParseResult.errors.length !== 0) { - updateReportDiagnostic(configParseResult.options); + reportDiagnostic = updateReportDiagnostic(sys, reportDiagnostic, configParseResult.options); configParseResult.errors.forEach(reportDiagnostic); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } // eslint-disable-next-line no-null/no-null - ts.sys.write(JSON.stringify(ts.convertToTSConfig(configParseResult, configFileName, ts.sys), null, 4) + ts.sys.newLine); - return ts.sys.exit(ts.ExitStatus.Success); + sys.write(JSON.stringify(ts.convertToTSConfig(configParseResult, configFileName, sys), null, 4) + sys.newLine); + return sys.exit(ts.ExitStatus.Success); } - updateReportDiagnostic(configParseResult.options); + reportDiagnostic = updateReportDiagnostic(sys, reportDiagnostic, configParseResult.options); if (ts.isWatchSet(configParseResult.options)) { - reportWatchModeWithoutSysSupport(); - createWatchOfConfigFile(configParseResult, commandLineOptions); + if (reportWatchModeWithoutSysSupport(sys, reportDiagnostic)) + return; + createWatchOfConfigFile(sys, reportDiagnostic, configParseResult, commandLineOptions); } else if (ts.isIncrementalCompilation(configParseResult.options)) { - performIncrementalCompilation(configParseResult); + performIncrementalCompilation(sys, reportDiagnostic, cb, configParseResult); } else { - performCompilation(configParseResult.fileNames, configParseResult.projectReferences, configParseResult.options, ts.getConfigFileParsingDiagnostics(configParseResult)); + performCompilation(sys, reportDiagnostic, cb, configParseResult); } } else { if (commandLineOptions.showConfig) { // eslint-disable-next-line no-null/no-null - ts.sys.write(JSON.stringify(ts.convertToTSConfig(commandLine, ts.combinePaths(ts.sys.getCurrentDirectory(), "tsconfig.json"), ts.sys), null, 4) + ts.sys.newLine); - return ts.sys.exit(ts.ExitStatus.Success); + sys.write(JSON.stringify(ts.convertToTSConfig(commandLine, ts.combinePaths(currentDirectory, "tsconfig.json"), sys), null, 4) + sys.newLine); + return sys.exit(ts.ExitStatus.Success); } - updateReportDiagnostic(commandLineOptions); + reportDiagnostic = updateReportDiagnostic(sys, reportDiagnostic, commandLineOptions); if (ts.isWatchSet(commandLineOptions)) { - reportWatchModeWithoutSysSupport(); - createWatchOfFilesAndCompilerOptions(commandLine.fileNames, commandLineOptions); + if (reportWatchModeWithoutSysSupport(sys, reportDiagnostic)) + return; + createWatchOfFilesAndCompilerOptions(sys, reportDiagnostic, commandLine.fileNames, commandLineOptions); } else if (ts.isIncrementalCompilation(commandLineOptions)) { - performIncrementalCompilation(commandLine); + performIncrementalCompilation(sys, reportDiagnostic, cb, __assign(__assign({}, commandLine), { options: commandLineOptions })); } else { - performCompilation(commandLine.fileNames, /*references*/ undefined, commandLineOptions); + performCompilation(sys, reportDiagnostic, cb, __assign(__assign({}, commandLine), { options: commandLineOptions })); } } } - function executeCommandLine(args) { - if (args.length > 0 && args[0].charCodeAt(0) === 45 /* minus */) { - var firstOption = args[0].slice(args[0].charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); - if (firstOption === "build" || firstOption === "b") { - return performBuild(args.slice(1)); - } + function isBuild(commandLineArgs) { + if (commandLineArgs.length > 0 && commandLineArgs[0].charCodeAt(0) === 45 /* minus */) { + var firstOption = commandLineArgs[0].slice(commandLineArgs[0].charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); + return firstOption === "build" || firstOption === "b"; } - var commandLine = ts.parseCommandLine(args); - if (commandLine.options.generateCpuProfile && ts.sys.enableCPUProfiler) { - ts.sys.enableCPUProfiler(commandLine.options.generateCpuProfile, function () { return executeCommandLineWorker(commandLine); }); + return false; + } + ts.isBuild = isBuild; + function executeCommandLine(system, cb, commandLineArgs) { + if (isBuild(commandLineArgs)) { + return performBuild(system, cb, commandLineArgs.slice(1)); + } + var commandLine = ts.parseCommandLine(commandLineArgs, function (path) { return system.readFile(path); }); + if (commandLine.options.generateCpuProfile && system.enableCPUProfiler) { + system.enableCPUProfiler(commandLine.options.generateCpuProfile, function () { return executeCommandLineWorker(system, cb, commandLine); }); } else { - executeCommandLineWorker(commandLine); + executeCommandLineWorker(system, cb, commandLine); } } ts.executeCommandLine = executeCommandLine; - function reportWatchModeWithoutSysSupport() { - if (!ts.sys.watchFile || !ts.sys.watchDirectory) { + function reportWatchModeWithoutSysSupport(sys, reportDiagnostic) { + if (!sys.watchFile || !sys.watchDirectory) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); - ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return true; } + return false; } - function performBuildWorker(buildOptions, projects, errors) { + function performBuildWorker(sys, cb, buildOptions, projects, errors) { // Update to pretty if host supports it - updateReportDiagnostic(buildOptions); + var reportDiagnostic = updateReportDiagnostic(sys, ts.createDiagnosticReporter(sys), buildOptions); if (buildOptions.locale) { - ts.validateLocaleAndSetLanguage(buildOptions.locale, ts.sys, errors); + ts.validateLocaleAndSetLanguage(buildOptions.locale, sys, errors); } if (errors.length > 0) { errors.forEach(reportDiagnostic); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (buildOptions.help) { - ts.printVersion(); - ts.printHelp(ts.buildOpts, "--build "); - return ts.sys.exit(ts.ExitStatus.Success); + printVersion(sys); + printHelp(sys, ts.buildOpts, "--build "); + return sys.exit(ts.ExitStatus.Success); } if (projects.length === 0) { - ts.printVersion(); - ts.printHelp(ts.buildOpts, "--build "); - return ts.sys.exit(ts.ExitStatus.Success); + printVersion(sys); + printHelp(sys, ts.buildOpts, "--build "); + return sys.exit(ts.ExitStatus.Success); } - if (!ts.sys.getModifiedTime || !ts.sys.setModifiedTime || (buildOptions.clean && !ts.sys.deleteFile)) { + if (!sys.getModifiedTime || !sys.setModifiedTime || (buildOptions.clean && !sys.deleteFile)) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (buildOptions.watch) { - reportWatchModeWithoutSysSupport(); - var buildHost_1 = ts.createSolutionBuilderWithWatchHost(ts.sys, /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty(buildOptions)), createWatchStatusReporter(buildOptions)); - updateCreateProgram(buildHost_1); - buildHost_1.afterProgramEmitAndDiagnostics = function (program) { return reportStatistics(program.getProgram()); }; + if (reportWatchModeWithoutSysSupport(sys, reportDiagnostic)) + return; + var buildHost_1 = ts.createSolutionBuilderWithWatchHost(sys, + /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(sys, shouldBePretty(sys, buildOptions)), createWatchStatusReporter(sys, buildOptions)); + if (cb && cb.onSolutionBuilderHostCreate) + cb.onSolutionBuilderHostCreate(buildHost_1); + updateCreateProgram(sys, buildHost_1); + buildHost_1.afterProgramEmitAndDiagnostics = function (program) { return reportStatistics(sys, program.getProgram()); }; var builder_1 = ts.createSolutionBuilderWithWatch(buildHost_1, projects, buildOptions); builder_1.build(); return; } - var buildHost = ts.createSolutionBuilderHost(ts.sys, /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty(buildOptions)), createReportErrorSummary(buildOptions)); - updateCreateProgram(buildHost); - buildHost.afterProgramEmitAndDiagnostics = function (program) { return reportStatistics(program.getProgram()); }; + var buildHost = ts.createSolutionBuilderHost(sys, + /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(sys, shouldBePretty(sys, buildOptions)), createReportErrorSummary(sys, buildOptions)); + if (cb && cb.onSolutionBuilderHostCreate) + cb.onSolutionBuilderHostCreate(buildHost); + updateCreateProgram(sys, buildHost); + buildHost.afterProgramEmitAndDiagnostics = function (program) { return reportStatistics(sys, program.getProgram()); }; var builder = ts.createSolutionBuilder(buildHost, projects, buildOptions); - return ts.sys.exit(buildOptions.clean ? builder.clean() : builder.build()); + var exitStatus = buildOptions.clean ? builder.clean() : builder.build(); + if (cb && cb.onSolutionBuildComplete) + cb.onSolutionBuildComplete(builder.getAllParsedConfigs()); + return sys.exit(exitStatus); } - function performBuild(args) { + function performBuild(sys, cb, args) { var _a = ts.parseBuildCommand(args), buildOptions = _a.buildOptions, projects = _a.projects, errors = _a.errors; - if (buildOptions.generateCpuProfile && ts.sys.enableCPUProfiler) { - ts.sys.enableCPUProfiler(buildOptions.generateCpuProfile, function () { return performBuildWorker(buildOptions, projects, errors); }); + if (buildOptions.generateCpuProfile && sys.enableCPUProfiler) { + sys.enableCPUProfiler(buildOptions.generateCpuProfile, function () { return performBuildWorker(sys, cb, buildOptions, projects, errors); }); } else { - performBuildWorker(buildOptions, projects, errors); + performBuildWorker(sys, cb, buildOptions, projects, errors); } } - function createReportErrorSummary(options) { - return shouldBePretty(options) ? - function (errorCount) { return ts.sys.write(ts.getErrorSummaryText(errorCount, ts.sys.newLine)); } : + function createReportErrorSummary(sys, options) { + return shouldBePretty(sys, options) ? + function (errorCount) { return sys.write(ts.getErrorSummaryText(errorCount, sys.newLine)); } : undefined; } - function performCompilation(rootNames, projectReferences, options, configFileParsingDiagnostics) { - var host = ts.createCompilerHost(options); + function performCompilation(sys, reportDiagnostic, cb, config) { + var fileNames = config.fileNames, options = config.options, projectReferences = config.projectReferences; + var host = ts.createCompilerHostWorker(options, /*setParentPos*/ undefined, sys); + if (cb && cb.onCompilerHostCreate) + cb.onCompilerHostCreate(host); var currentDirectory = host.getCurrentDirectory(); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); }); - enableStatistics(options); + enableStatistics(sys, options); var programOptions = { - rootNames: rootNames, + rootNames: fileNames, options: options, projectReferences: projectReferences, host: host, - configFileParsingDiagnostics: configFileParsingDiagnostics + configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(config) }; var program = ts.createProgram(programOptions); - var exitStatus = ts.emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, function (s) { return ts.sys.write(s + ts.sys.newLine); }, createReportErrorSummary(options)); - reportStatistics(program); - return ts.sys.exit(exitStatus); + var exitStatus = ts.emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, function (s) { return sys.write(s + sys.newLine); }, createReportErrorSummary(sys, options)); + reportStatistics(sys, program); + if (cb && cb.onCompilationComplete) + cb.onCompilationComplete(config); + return sys.exit(exitStatus); } - function performIncrementalCompilation(config) { + function performIncrementalCompilation(sys, reportDiagnostic, cb, config) { var options = config.options, fileNames = config.fileNames, projectReferences = config.projectReferences; - enableStatistics(options); - return ts.sys.exit(ts.performIncrementalCompilation({ + enableStatistics(sys, options); + var host = ts.createIncrementalCompilerHost(options, sys); + if (cb && cb.onCompilerHostCreate) + cb.onCompilerHostCreate(host); + var exitStatus = ts.performIncrementalCompilation({ + host: host, + system: sys, rootNames: fileNames, options: options, configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(config), projectReferences: projectReferences, reportDiagnostic: reportDiagnostic, - reportErrorSummary: createReportErrorSummary(options), - afterProgramEmitAndDiagnostics: function (builderProgram) { return reportStatistics(builderProgram.getProgram()); } - })); + reportErrorSummary: createReportErrorSummary(sys, options), + afterProgramEmitAndDiagnostics: function (builderProgram) { return reportStatistics(sys, builderProgram.getProgram()); } + }); + if (cb && cb.onCompilationComplete) + cb.onCompilationComplete(config); + return sys.exit(exitStatus); } - function updateCreateProgram(host) { + function updateCreateProgram(sys, host) { var compileUsingBuilder = host.createProgram; host.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) { ts.Debug.assert(rootNames !== undefined || (options === undefined && !!oldProgram)); if (options !== undefined) { - enableStatistics(options); + enableStatistics(sys, options); } return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); }; } - function updateWatchCompilationHost(watchCompilerHost) { - updateCreateProgram(watchCompilerHost); + function updateWatchCompilationHost(sys, watchCompilerHost) { + updateCreateProgram(sys, watchCompilerHost); var emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate; // TODO: GH#18217 watchCompilerHost.afterProgramCreate = function (builderProgram) { emitFilesUsingBuilder(builderProgram); - reportStatistics(builderProgram.getProgram()); + reportStatistics(sys, builderProgram.getProgram()); }; } - function createWatchStatusReporter(options) { - return ts.createWatchStatusReporter(ts.sys, shouldBePretty(options)); + function createWatchStatusReporter(sys, options) { + return ts.createWatchStatusReporter(sys, shouldBePretty(sys, options)); } - function createWatchOfConfigFile(configParseResult, optionsToExtend) { - var watchCompilerHost = ts.createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath, optionsToExtend, ts.sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(configParseResult.options)); // TODO: GH#18217 - updateWatchCompilationHost(watchCompilerHost); + function createWatchOfConfigFile(sys, reportDiagnostic, configParseResult, optionsToExtend) { + var watchCompilerHost = ts.createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath, optionsToExtend, sys, + /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(sys, configParseResult.options)); // TODO: GH#18217 + updateWatchCompilationHost(sys, watchCompilerHost); watchCompilerHost.configFileParsingResult = configParseResult; ts.createWatchProgram(watchCompilerHost); } - function createWatchOfFilesAndCompilerOptions(rootFiles, options) { - var watchCompilerHost = ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, ts.sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(options)); - updateWatchCompilationHost(watchCompilerHost); + function createWatchOfFilesAndCompilerOptions(sys, reportDiagnostic, rootFiles, options) { + var watchCompilerHost = ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, sys, + /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(sys, options)); + updateWatchCompilationHost(sys, watchCompilerHost); ts.createWatchProgram(watchCompilerHost); } - function enableStatistics(compilerOptions) { - if (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics) { + function canReportDiagnostics(system, compilerOptions) { + return system === ts.sys && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); + } + function enableStatistics(sys, compilerOptions) { + if (canReportDiagnostics(sys, compilerOptions)) { ts.performance.enable(); } } - function reportStatistics(program) { + function reportStatistics(sys, program) { var statistics; var compilerOptions = program.getCompilerOptions(); - if (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics) { + if (canReportDiagnostics(sys, compilerOptions)) { statistics = []; - var memoryUsed = ts.sys.getMemoryUsage ? ts.sys.getMemoryUsage() : -1; + var memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1; reportCountStatistic("Files", program.getSourceFiles().length); reportCountStatistic("Lines", countLines(program)); reportCountStatistic("Nodes", program.getNodeCount()); @@ -84325,7 +84671,7 @@ var ts; } for (var _b = 0, statistics_2 = statistics; _b < statistics_2.length; _b++) { var _c = statistics_2[_b], name = _c.name, value = _c.value; - ts.sys.write(padRight(name + ":", nameSize + 2) + padLeft(value.toString(), valueSize) + ts.sys.newLine); + sys.write(padRight(name + ":", nameSize + 2) + padLeft(value.toString(), valueSize) + sys.newLine); } } function reportStatisticalValue(name, value) { @@ -84338,14 +84684,14 @@ var ts; reportStatisticalValue(name, (time / 1000).toFixed(2) + "s"); } } - function writeConfigFile(options, fileNames) { - var currentDirectory = ts.sys.getCurrentDirectory(); + function writeConfigFile(sys, reportDiagnostic, options, fileNames) { + var currentDirectory = sys.getCurrentDirectory(); var file = ts.normalizePath(ts.combinePaths(currentDirectory, "tsconfig.json")); - if (ts.sys.fileExists(file)) { + if (sys.fileExists(file)) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file)); } else { - ts.sys.writeFile(file, ts.generateTSConfig(options, fileNames, ts.sys.newLine)); + sys.writeFile(file, ts.generateTSConfig(options, fileNames, sys.newLine)); reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Successfully_created_a_tsconfig_json_file)); } return; @@ -84360,4 +84706,10 @@ if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnviron if (ts.sys.setBlocking) { ts.sys.setBlocking(); } -ts.executeCommandLine(ts.sys.args); +// This file actually uses arguments passed on commandline and executes it +ts.executeCommandLine(ts.sys, { + onCompilerHostCreate: ts.noop, + onCompilationComplete: ts.noop, + onSolutionBuilderHostCreate: ts.noop, + onSolutionBuildComplete: ts.noop +}, ts.sys.args); diff --git a/lib/tsserver.js b/lib/tsserver.js index 6e974402749..2c794d3fbc9 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -92,7 +92,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.7"; + ts.versionMajorMinor = "3.8"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -107,22 +107,32 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; - /** Create a MapLike with good performance. */ - function createDictionaryObject() { - var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - return map; + /** + * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). + */ + function tryGetNativeMap() { + // Internet Explorer's Map doesn't support iteration, so don't use it. + // eslint-disable-next-line no-in-operator + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; } - /** Create a new map. If a template object is provided, the map will copy entries from it. */ + ts.tryGetNativeMap = tryGetNativeMap; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + ts.Map = ts.tryGetNativeMap() || (function () { + // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it. + if (typeof ts.createMapShim === "function") { + return ts.createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); + /** Create a new map. */ function createMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createMap = createMap; + /** Create a new map from an array of entries. */ function createMapFromEntries(entries) { var map = createMap(); for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { @@ -132,8 +142,9 @@ var ts; return map; } ts.createMapFromEntries = createMapFromEntries; + /** Create a new map from a template object is provided, the map will copy entries from it. */ function createMapFromTemplate(template) { - var map = new ts.MapCtr(); + var map = new ts.Map(); // Copies keys/values from template. Note that for..in will not throw if // template is undefined, and instead will just exit the loop. for (var key in template) { @@ -144,147 +155,6 @@ var ts; return map; } ts.createMapFromTemplate = createMapFromTemplate; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // eslint-disable-next-line no-in-operator - ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - // Keep the class inside a function so it doesn't get compiled if it's not used. - function shimMap() { - var MapIterator = /** @class */ (function () { - function MapIterator(currentEntry, selector) { - this.currentEntry = currentEntry; - this.selector = selector; - } - MapIterator.prototype.next = function () { - // Navigate to the next entry. - while (this.currentEntry) { - var skipNext = !!this.currentEntry.skipNext; - this.currentEntry = this.currentEntry.nextEntry; - if (!skipNext) { - break; - } - } - if (this.currentEntry) { - return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false }; - } - else { - return { value: undefined, done: true }; - } - }; - return MapIterator; - }()); - return /** @class */ (function () { - function class_1() { - this.data = createDictionaryObject(); - this.size = 0; - // Create a first (stub) map entry that will not contain a key - // and value but serves as starting point for iterators. - this.firstEntry = {}; - // When the map is empty, the last entry is the same as the - // first one. - this.lastEntry = this.firstEntry; - } - class_1.prototype.get = function (key) { - var entry = this.data[key]; - return entry && entry.value; - }; - class_1.prototype.set = function (key, value) { - if (!this.has(key)) { - this.size++; - // Create a new entry that will be appended at the - // end of the linked list. - var newEntry = { - key: key, - value: value - }; - this.data[key] = newEntry; - // Adjust the references. - var previousLastEntry = this.lastEntry; - previousLastEntry.nextEntry = newEntry; - newEntry.previousEntry = previousLastEntry; - this.lastEntry = newEntry; - } - else { - this.data[key].value = value; - } - return this; - }; - class_1.prototype.has = function (key) { - // eslint-disable-next-line no-in-operator - return key in this.data; - }; - class_1.prototype.delete = function (key) { - if (this.has(key)) { - this.size--; - var entry = this.data[key]; - delete this.data[key]; - // Adjust the linked list references of the neighbor entries. - var previousEntry = entry.previousEntry; - previousEntry.nextEntry = entry.nextEntry; - if (entry.nextEntry) { - entry.nextEntry.previousEntry = previousEntry; - } - // When the deleted entry was the last one, we need to - // adjust the lastEntry reference. - if (this.lastEntry === entry) { - this.lastEntry = previousEntry; - } - // Adjust the forward reference of the deleted entry - // in case an iterator still references it. This allows us - // to throw away the entry, but when an active iterator - // (which points to the current entry) continues, it will - // navigate to the entry that originally came before the - // current one and skip it. - entry.previousEntry = undefined; - entry.nextEntry = previousEntry; - entry.skipNext = true; - return true; - } - return false; - }; - class_1.prototype.clear = function () { - this.data = createDictionaryObject(); - this.size = 0; - // Reset the linked list. Note that we must adjust the forward - // references of the deleted entries to ensure iterators stuck - // in the middle of the list don't continue with deleted entries, - // but can continue with new entries added after the clear() - // operation. - var firstEntry = this.firstEntry; - var currentEntry = firstEntry.nextEntry; - while (currentEntry) { - var nextEntry = currentEntry.nextEntry; - currentEntry.previousEntry = undefined; - currentEntry.nextEntry = firstEntry; - currentEntry.skipNext = true; - currentEntry = nextEntry; - } - firstEntry.nextEntry = undefined; - this.lastEntry = firstEntry; - }; - class_1.prototype.keys = function () { - return new MapIterator(this.firstEntry, function (key) { return key; }); - }; - class_1.prototype.values = function () { - return new MapIterator(this.firstEntry, function (_key, value) { return value; }); - }; - class_1.prototype.entries = function () { - return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; }); - }; - class_1.prototype.forEach = function (action) { - var iterator = this.entries(); - while (true) { - var iterResult = iterator.next(); - if (iterResult.done) { - break; - } - var _a = iterResult.value, key = _a[0], value = _a[1]; - action(value, key); - } - }; - return class_1; - }()); - } - ts.shimMap = shimMap; function length(array) { return array ? array.length : 0; } @@ -1866,20 +1736,6 @@ var ts; return str.indexOf(substring) !== -1; } ts.stringContains = stringContains; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -2193,11 +2049,14 @@ var ts; if (isFlags) { var result = ""; var remainingFlags = value; - for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { - var _a = members[i], enumValue = _a[0], enumName = _a[1]; - if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; + if (enumValue > value) { + break; + } + if (enumValue !== 0 && enumValue & value) { + result = "" + result + (result ? "|" : "") + enumName; remainingFlags &= ~enumValue; - result = "" + enumName + (result ? "|" : "") + result; } } if (remainingFlags === 0) { @@ -2205,8 +2064,8 @@ var ts; } } else { - for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { - var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + for (var _b = 0, members_2 = members; _b < members_2.length; _b++) { + var _c = members_2[_b], enumValue = _c[0], enumName = _c[1]; if (enumValue === value) { return enumName; } @@ -2280,6 +2139,33 @@ var ts; ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; var isDebugInfoEnabled = false; + var extendedDebugModule; + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + Debug.formatControlFlowGraph = formatControlFlowGraph; + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator + Object.defineProperties(flowNode, { + __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } }, + __debugToString: { value: function () { return formatControlFlowGraph(this); } } + }); + } + } + } + Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; /** * Injects debug information into frequently used types. */ @@ -2323,6 +2209,20 @@ var ts; }); } } + // attempt to load extended debugging information + try { + if (ts.sys && ts.sys.require) { + var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath())); + var result = ts.sys.require(basePath, "./compiler-debug"); + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch (_a) { + // do nothing + } isDebugInfoEnabled = true; } Debug.enableDebugInfo = enableDebugInfo; @@ -2486,8 +2386,6 @@ var ts; } /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - var args = typeof process === "undefined" ? [] : process.argv; - ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(args)); })(ts || (ts = {})); /* @internal */ var ts; @@ -3382,6 +3280,7 @@ var ts; /* @internal */ TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + // NOTE: Ensure this is up-to-date with src/debug/debug.ts var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -3437,6 +3336,8 @@ var ts; // When build skipped because passed in project is invalid ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped"; // When build is skipped because project references form cycle + ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ @@ -3446,6 +3347,14 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + /* @internal */ + var ContextFlags; + (function (ContextFlags) { + ContextFlags[ContextFlags["None"] = 0] = "None"; + ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; + ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; + ContextFlags[ContextFlags["Completion"] = 4] = "Completion"; + })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {})); // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { @@ -3848,19 +3757,20 @@ var ts; ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 131072] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 262144] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 524288] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 1048576] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 786432] = "RequiresWidening"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 1835008] = "PropagatingFlags"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -3887,6 +3797,20 @@ var ts; SignatureKind[SignatureKind["Call"] = 0] = "Call"; SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + /* @internal */ + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter"; + SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes"; + SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain"; + SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain"; + // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us + // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when + // instantiating the return type. + SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags"; + SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags"; + })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {})); var IndexKind; (function (IndexKind) { IndexKind[IndexKind["String"] = 0] = "String"; @@ -4887,16 +4811,6 @@ var ts; } } ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; - function recursiveCreateDirectory(directoryPath, sys) { - var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); - if (shouldCreateParent) { - recursiveCreateDirectory(basePath, sys); - } - if (shouldCreateParent || !sys.directoryExists(directoryPath)) { - sys.createDirectory(directoryPath); - } - } /** * patch writefile to create folder before writing the file */ @@ -4905,11 +4819,7 @@ var ts; // patch writefile to create folder before writing the file var originalWriteFile = sys.writeFile; sys.writeFile = function (path, data, writeBom) { - var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); - if (directoryPath && !sys.directoryExists(directoryPath)) { - recursiveCreateDirectory(directoryPath, sys); - } - originalWriteFile.call(sys, path, data, writeBom); + return ts.writeFileEnsuringDirectories(path, data, !!writeBom, function (path, data, writeByteOrderMark) { return originalWriteFile.call(sys, path, data, writeByteOrderMark); }, function (path) { return sys.createDirectory(path); }, function (path) { return sys.directoryExists(path); }); }; } ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory; @@ -5058,6 +4968,15 @@ var ts; bufferFrom: bufferFrom, base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + require: function (baseDir, moduleName) { + try { + var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath: modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error: error }; + } + } }; return nodeSystem; /** @@ -5196,6 +5115,7 @@ var ts; if (fsSupportsRecursive) { return watchDirectoryUsingFsWatch; } + // defer watchDirectoryRecursively as it depends on `ts.createMap()` which may not be usable yet. var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? createWatchDirectoryUsing(fsWatchFile) : tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? @@ -5640,6 +5560,673 @@ var ts; ts.Debug.isDebugging = true; } })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + //// Path Tests + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + //// Path Parsing + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArrays([root], rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + //// Path Formatting + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + //// Path Normalization + /** + * Normalize path separators, converting `\` into `/`. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + //// Path Comparisons + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * @deprecated Use `containsPath` if possible. + */ + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + //// Relative Paths + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArrays([""], relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; +})(ts || (ts = {})); // // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ @@ -5667,7 +6254,7 @@ var ts; An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), - An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), @@ -5875,7 +6462,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd_1323", "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5911,6 +6498,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"), 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), @@ -6038,7 +6626,6 @@ var ts; Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), @@ -6208,8 +6795,8 @@ var ts; JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2610, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_proper_2610", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member property."), - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2611, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_access_2611", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member accessor."), + _0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property: diag(2610, ts.DiagnosticCategory.Error, "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610", "'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property."), + _0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor: diag(2611, ts.DiagnosticCategory.Error, "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611", "'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor."), Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), @@ -6432,6 +7019,8 @@ var ts; Parameter_0_of_accessor_has_or_is_using_private_name_1: diag(4106, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106", "Parameter '{0}' of accessor has or is using private name '{1}'."), Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2: diag(4107, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107", "Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'."), Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4108, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108", "Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named."), + Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), + Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -6439,6 +7028,7 @@ var ts; Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Unknown_compiler_option_0_Did_you_mean_1: diag(5025, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"), Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), @@ -6469,6 +7059,7 @@ var ts; 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}'?"), 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."), @@ -6515,7 +7106,7 @@ var ts; Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has an unsupported extension. The only supported extensions are {1}."), Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), @@ -6723,6 +7314,8 @@ var ts; 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."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), + File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -6826,6 +7419,7 @@ var ts; Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), + Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"), Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), @@ -9058,7 +9652,7 @@ var ts; ts.getDeclarationOfKind = getDeclarationOfKind; /** Create a new escaped identifier map. */ function createUnderscoreEscapedMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; function hasEntries(map) { @@ -9114,13 +9708,6 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -9927,6 +10514,11 @@ var ts; break; case 201 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); + case 275 /* CaseClause */: + case 276 /* DefaultClause */: + var start = ts.skipTrivia(sourceFile.text, node.pos); + var end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return ts.createTextSpanFromBounds(start, end); } if (errorNode === undefined) { // If we don't have a better node, then just set the error on the first token of @@ -10739,7 +11331,7 @@ var ts; (node.typeArguments[0].kind === 142 /* StringKeyword */ || node.typeArguments[0].kind === 139 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 195 /* CallExpression */) { return false; } @@ -10751,7 +11343,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -10973,27 +11565,31 @@ var ts; isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true); } ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; - function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { - return isLiteralLikeElementAccess(node) - && ((!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */) || - isEntityNameExpression(node.expression) || - isBindableStaticElementAccessExpression(node.expression, /*excludeThisKeyword*/ true)); - } - ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression; + /** x.y OR x[0] */ function isLiteralLikeAccess(node) { return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node); } ts.isLiteralLikeAccess = isLiteralLikeAccess; + /** x[0] OR x['a'] OR x[Symbol.y] */ function isLiteralLikeElementAccess(node) { return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) || isWellKnownSymbolSyntactically(node.argumentExpression)); } ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; + /** Any series of property and element accesses. */ function isBindableStaticAccessExpression(node, excludeThisKeyword) { return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */ || isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; + /** Any series of property and element accesses, ending in a literal element access */ + function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { + return isLiteralLikeElementAccess(node) + && ((!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */) || + isEntityNameExpression(node.expression) || + isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true)); + } + ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression; function isBindableStaticNameExpression(node, excludeThisKeyword) { return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword); } @@ -11022,7 +11618,7 @@ var ts; if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) { return 0 /* None */; } - if (isBindableStaticNameExpression(expr.left.expression) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { // F.prototype = { ... } return 6 /* Prototype */; } @@ -11078,13 +11674,17 @@ var ts; nextToLast = nextToLast.expression; } var id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { - // exports.name = expr OR module.exports.name = expr + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + // ExportsProperty does not support binding with computed names + isBindableStaticAccessExpression(lhs)) { + // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return 1 /* ExportsProperty */; } - // F.G...x = expr - return 5 /* Property */; + if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs) && lhs.expression.kind !== 103 /* ThisKeyword */)) { + // F.G...x = expr + return 5 /* Property */; + } } return 0 /* None */; } @@ -12406,7 +13006,7 @@ var ts; */ function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); var extensionless = ts.removeFileExtension(relativePath); @@ -12489,6 +13089,25 @@ var ts; }, sourceFiles); } ts.writeFile = writeFile; + function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists); + createDirectory(directoryPath); + } + } + function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) { + // PERF: Checking for directory existence is expensive. Instead, assume the directory exists + // and fall back to creating it if the file write fails. + try { + writeFile(path, data, writeByteOrderMark); + } + catch (_a) { + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists); + writeFile(path, data, writeByteOrderMark); + } + } + ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories; function getLineOfLocalPosition(currentSourceFile, pos) { return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; } @@ -12928,6 +13547,23 @@ var ts; return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function getFirstIdentifier(node) { + switch (node.kind) { + case 75 /* Identifier */: + return node; + case 152 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 75 /* Identifier */); + return node; + case 193 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 75 /* Identifier */); + return node; + } + } + ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { return node.kind === 75 /* Identifier */ || node.kind === 103 /* ThisKeyword */ || node.kind === 193 /* PropertyAccessExpression */ && isDottedName(node.expression) || @@ -13446,20 +14082,6 @@ var ts; }); } ts.mutateMap = mutateMap; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); @@ -13486,7 +14108,7 @@ var ts; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { @@ -14551,11 +15173,47 @@ var ts; } ts.isCallChain = isCallChain; function isOptionalChain(node) { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + var kind = node.kind; + return !!(node.flags & 32 /* OptionalChain */) && + (kind === 193 /* PropertyAccessExpression */ + || kind === 194 /* ElementAccessExpression */ + || kind === 195 /* CallExpression */); } ts.isOptionalChain = isOptionalChain; + /* @internal */ + function isOptionalChainRoot(node) { + return isOptionalChain(node) && !!node.questionDotToken; + } + ts.isOptionalChainRoot = isOptionalChainRoot; + /** + * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`). + */ + /* @internal */ + function isExpressionOfOptionalChainRoot(node) { + return isOptionalChainRoot(node.parent) && node.parent.expression === node; + } + ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot; + /** + * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`: + * + * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`) + * 2. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain) + * 3. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is + * the end of the chain starting at `c?.`) + * 4. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is + * the end of the chain starting at `a?.`) + */ + /* @internal */ + function isOutermostOptionalChain(node) { + return !isOptionalChain(node.parent) // cases 1 and 2 + || isOptionalChainRoot(node.parent) // case 3 + || node !== node.parent.expression; // case 4 + } + ts.isOutermostOptionalChain = isOutermostOptionalChain; + function isNullishCoalesce(node) { + return node.kind === 208 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; + } + ts.isNullishCoalesce = isNullishCoalesce; function isNewExpression(node) { return node.kind === 196 /* NewExpression */; } @@ -15826,11 +16484,6 @@ var ts; return node.kind === 162 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; - /* @internal */ - function isOptionalChainRoot(node) { - return ts.isOptionalChain(node) && !!node.questionDotToken; - } - ts.isOptionalChainRoot = isOptionalChainRoot; /** True if has jsdoc nodes attached to it. */ /* @internal */ // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times @@ -15917,7 +16570,12 @@ var ts; this.checker = checker; } } - function Signature() { } + function Signature(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } function Node(kind, pos, end) { this.pos = pos; this.end = end; @@ -16192,273 +16850,6 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - /** - * Normalize path separators. - */ - function normalizeSlashes(path) { - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - function isVolumeCharacter(charCode) { - return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || - (charCode >= 65 /* A */ && charCode <= 90 /* Z */); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; - if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; - } - return -1; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - // POSIX or UNC - if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; // POSIX: "/" (or non-normalized "\") - var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; // UNC: "//server" or "\\server" - return p1 + 1; // UNC: "//server/" or "\\server\" - } - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) - return 2; // DOS: "c:" (but not "c:d") - } - // URL - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - // relative - return 0; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - // TODO(rbuckton): replace references with `resolvePath` - function normalizePath(path) { - return ts.resolvePath(path); - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - // If the path provided is itself the root, then return it. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = ts.removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - /** - * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArrays([root], rest); - } - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = ts.combinePaths(currentDirectory, path); - var rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - ts.getPathComponents = getPathComponents; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - */ - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var result = ts.createMap(); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { @@ -16475,15 +16866,15 @@ var ts; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { aParts.pop(); bParts.pop(); } - return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; } // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. @@ -16493,229 +16884,8 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); - var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArrays([""], relative, components); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - */ - function ensurePathIsNonModuleName(path) { - return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function getBaseFileName(path, extensions, ignoreCase) { - path = ts.normalizeSlashes(path); - // if the path provided is itself the root, then it has not file name. - var rootLength = ts.getRootLength(path); - if (rootLength === path.length) - return ""; - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - /** - * Combines paths. If a path is absolute, it replaces any previous path. - */ - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = ts.normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = ts.normalizeSlashes(relativePath); - if (!path || ts.getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. - */ - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - var combined = ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : ts.normalizeSlashes(path); - var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.resolvePath = resolvePath; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path) { - if (path.length === 0) - return false; - var ch = path.charCodeAt(path.length - 1); - return ch === 47 /* slash */ || ch === 92 /* backslash */; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - // check path for these segments: '', '.'. '..' - var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - var aRoot = a.substring(0, ts.getRootLength(a)); - var bRoot = b.substring(0, ts.getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0 /* EqualTo */) { - return result; - } - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); - var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_1 = componentComparer(aComponents[i], bComponents[i]); - if (result_1 !== 0 /* EqualTo */) { - return result_1; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - /** - * Performs a case-sensitive comparison of two paths. - */ - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); - var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function isDirectorySeparator(charCode) { - return charCode === 47 /* slash */ || charCode === 92 /* backslash */; - } function stripLeadingDirectorySeparator(s) { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); @@ -16734,10 +16904,6 @@ var ts; return "\\" + match; } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -16813,7 +16979,7 @@ var ts; } // getNormalizedPathComponents includes the separator for the root component. // We need to remove to create our regex correctly. - components[0] = removeTrailingDirectorySeparator(components[0]); + components[0] = ts.removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); } @@ -16875,7 +17041,7 @@ var ts; function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); + var absolutePath = ts.combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), @@ -16904,7 +17070,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -16914,8 +17080,8 @@ var ts; visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) @@ -16942,8 +17108,8 @@ var ts; } for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { visitDirectory(name, absoluteName, depth); @@ -16965,14 +17131,14 @@ var ts; var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") - var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include)); // Append the literal and canonical candidate base paths. includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -16989,9 +17155,9 @@ var ts; var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { // No "*" or "?" in the path - return !hasExtension(absolute) + return !ts.hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -17063,10 +17229,6 @@ var ts; return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJSFileExtension = hasJSFileExtension; - function hasJSOrJsonFileExtension(fileName) { - return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); - } - ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; function hasTSFileExtension(fileName) { return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -17156,14 +17318,9 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); @@ -17206,36 +17363,6 @@ var ts; return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") - extensions = [extensions]; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -18443,6 +18570,9 @@ var ts; function doInYieldAndAwaitContext(func) { return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func); } + function doOutsideOfYieldAndAwaitContext(func) { + return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func); + } function inContext(flags) { return (contextFlags & flags) !== 0; } @@ -22714,18 +22844,7 @@ var ts; node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); - // For instance properties specifically, since they are evaluated inside the constructor, - // we do *not * want to parse yield expressions, so we specifically turn the yield context - // off. The grammar would look something like this: - // - // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; - // - // The checker may still error in the static case to explicitly disallow the yield expression. - node.initializer = ts.hasModifier(node, 32 /* Static */) - ? allowInAnd(parseInitializer) - : doOutsideOfContext(8192 /* YieldContext */ | 4096 /* DisallowInContext */, parseInitializer); + node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer); parseSemicolon(); return finishNode(node); } @@ -23016,7 +23135,7 @@ var ts; parseExpected(87 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(18 /* OpenBraceToken */)) { - node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); }); parseExpected(19 /* CloseBraceToken */); } else { @@ -25078,6 +25197,15 @@ var ts; isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, // Basic { name: "target", @@ -25909,8 +26037,7 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { - var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; + function parseCommandLineWorker(getOptionNameMap, diagnostics, commandLine, readFile) { var options = {}; var fileNames = []; var errors = []; @@ -25937,7 +26064,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); + errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -25973,7 +26100,13 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); + var possibleOption = ts.getSpellingSuggestion(s, ts.optionDeclarations, function (opt) { return "--" + opt.name; }); + if (possibleOption) { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownDidYouMeanDiagnostic, s, possibleOption.name)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownOptionDiagnostic, s)); + } } } else { @@ -26016,11 +26149,13 @@ var ts; parseStrings(args); } } + var compilerOptionsDefaultDiagnostics = { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument + }; function parseCommandLine(commandLine, readFile) { - return parseCommandLineWorker(getOptionNameMap, [ - ts.Diagnostics.Unknown_compiler_option_0, - ts.Diagnostics.Compiler_option_0_expects_an_argument - ], commandLine, readFile); + return parseCommandLineWorker(getOptionNameMap, compilerOptionsDefaultDiagnostics, commandLine, readFile); } ts.parseCommandLine = parseCommandLine; /** @internal */ @@ -26045,10 +26180,11 @@ var ts; function parseBuildCommand(args) { var buildOptionNameMap; var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; - var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ - ts.Diagnostics.Unknown_build_option_0, - ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 - ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + }, args), options = _a.options, projects = _a.fileNames, errors = _a.errors; var buildOptions = options; if (projects.length === 0) { // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." @@ -26070,6 +26206,7 @@ var ts; return { buildOptions: buildOptions, projects: projects, errors: errors }; } ts.parseBuildCommand = parseBuildCommand; + /* @internal */ function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -26078,104 +26215,7 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - /* @internal */ - function printVersion() { - ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); - } - ts.printVersion = printVersion; - /* @internal */ - function printHelp(optionsList, syntaxPrefix) { - if (syntaxPrefix === void 0) { syntaxPrefix = ""; } - var output = []; - // We want to align our "syntax" and "examples" commands to a certain margin. - var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); - // Build up the syntactic skeleton. - var syntax = makePadding(marginLength - syntaxLength); - syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; - output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); - output.push(ts.sys.newLine + ts.sys.newLine); - // Build up the list of examples. - var padding = makePadding(marginLength); - output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); - output.push(padding + "tsc @args.txt" + ts.sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); - output.push(ts.sys.newLine); - output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); - // We want our descriptions to align at the same column in our output, - // so we keep track of the longest option usage string. - marginLength = 0; - var usageColumn = []; // Things like "-d, --declaration" go in here. - var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind - for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { - var option = optionsList_1[_i]; - // If an option lacks a description, - // it is not officially supported. - if (!option.description) { - continue; - } - var usageText_1 = " "; - if (option.shortName) { - usageText_1 += "-" + option.shortName; - usageText_1 += getParamType(option); - usageText_1 += ", "; - } - usageText_1 += "--" + option.name; - usageText_1 += getParamType(option); - usageColumn.push(usageText_1); - var description = void 0; - if (option.name === "lib") { - description = getDiagnosticText(option.description); - var element = option.element; - var typeMap = element.type; - optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); - } - else { - description = getDiagnosticText(option.description); - } - descriptionColumn.push(description); - // Set the new margin for the description column if necessary. - marginLength = Math.max(usageText_1.length, marginLength); - } - // Special case that can't fit in the loop. - var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; - var kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { - var kind = kindsList_1[_a]; - output.push(kind + " "); - } - output.push(ts.sys.newLine); - } - } - for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { - var line = output_1[_b]; - ts.sys.write(line); - } - return; - function getParamType(option) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - } - ts.printHelp = printHelp; + ts.getDiagnosticText = getDiagnosticText; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -26259,19 +26299,28 @@ var ts; name: "compilerOptions", type: "object", elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1 + }, }, { name: "typingOptions", type: "object", elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 + }, }, { name: "typeAcquisition", type: "object", elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 + } }, { name: "extends", @@ -26336,7 +26385,7 @@ var ts; function isRootOptionMap(knownOptions) { return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } - function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; @@ -26353,8 +26402,19 @@ var ts; var textOfKey = ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; - if (keyText && extraKeyDiagnosticMessage && !option) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + if (keyText && extraKeyDiagnostics && !option) { + if (knownOptions) { + var possibleOption = ts.getSpellingSuggestion(keyText, ts.arrayFrom(knownOptions.keys()), ts.identity); + if (possibleOption) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownDidYouMeanDiagnostic, keyText, possibleOption)); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } } var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { @@ -26438,8 +26498,8 @@ var ts; // vs what we set in the json // If need arises, we can modify this interface and callbacks as needed if (option) { - var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; - return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName); } else { return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, @@ -26494,7 +26554,7 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign(__assign({ compilerOptions: __assign(__assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; @@ -26515,12 +26575,12 @@ var ts; return undefined; return specs; } - function matchesSpecs(path, includeSpecs, excludeSpecs) { + function matchesSpecs(path, includeSpecs, excludeSpecs, host) { if (!includeSpecs) return function (_) { return true; }; - var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); - var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); - var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; @@ -26697,6 +26757,35 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + /* @internal */ + function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + var result = {}; + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name in options) { + if (ts.hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; + function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option) { + if (option.type === "list") { + var values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value); + } + } + return value; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -27085,7 +27174,7 @@ var ts; } function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); - convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, compilerOptionsDefaultDiagnostics, errors); if (configFileName) { options.configFilePath = ts.normalizeSlashes(configFileName); } @@ -27097,10 +27186,14 @@ var ts; function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); - convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + var diagnostics = { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1, + }; + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, diagnostics, errors); return options; } - function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnostics, errors) { if (!jsonOptions) { return; } @@ -27111,7 +27204,13 @@ var ts; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } else { - errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + var possibleOption = ts.getSpellingSuggestion(id, optionDeclarations, function (opt) { return opt.name; }); + if (possibleOption) { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownDidYouMeanDiagnostic, id, possibleOption.name)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownOptionDiagnostic, id)); + } } } } @@ -27147,7 +27246,7 @@ var ts; } function normalizeNonListOptionValue(option, basePath, value) { if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + value = ts.getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } @@ -28931,7 +29030,10 @@ var ts; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); - var flowNodeCreated = ts.identity; + function initFlowNode(node) { + ts.Debug.attachFlowNodeDebugInfo(node); + return node; + } var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -28960,6 +29062,7 @@ var ts; var currentReturnTarget; var currentTrueTarget; var currentFalseTarget; + var currentExceptionTarget; var preSwitchCaseFlow; var activeLabels; var hasExplicitReturn; @@ -28995,6 +29098,9 @@ var ts; symbolCount = 0; skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); + // Attach debugging information if necessary + ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); + ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -29017,6 +29123,7 @@ var ts; currentReturnTarget = undefined; currentTrueTarget = undefined; currentFalseTarget = undefined; + currentExceptionTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; emitFlags = 0 /* None */; @@ -29338,11 +29445,11 @@ var ts; blockScopeContainer.locals = undefined; } if (containerFlags & 4 /* IsControlFlowContainer */) { - var saveFlowNodeCreated = flowNodeCreated; var saveCurrentFlow = currentFlow; var saveBreakTarget = currentBreakTarget; var saveContinueTarget = currentContinueTarget; var saveReturnTarget = currentReturnTarget; + var saveExceptionTarget = currentExceptionTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && @@ -29350,7 +29457,7 @@ var ts; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isIIFE) { - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.node = node; } @@ -29358,11 +29465,11 @@ var ts; // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. currentReturnTarget = isIIFE || node.kind === 161 /* Constructor */ ? createBranchLabel() : undefined; + currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = ts.identity; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~2816 /* ReachabilityAndEmitFlags */; @@ -29388,9 +29495,9 @@ var ts; currentBreakTarget = saveBreakTarget; currentContinueTarget = saveContinueTarget; currentReturnTarget = saveReturnTarget; + currentExceptionTarget = saveExceptionTarget; activeLabels = saveActiveLabels; hasExplicitReturn = saveHasExplicitReturn; - flowNodeCreated = saveFlowNodeCreated; } else if (containerFlags & 64 /* IsInterface */) { seenThisKeyword = false; @@ -29531,9 +29638,6 @@ var ts; case 309 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; - case 307 /* JSDocClassTag */: - bindJSDocClassTag(node); - break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 288 /* SourceFile */: { bindEachFunctionsFirst(node.statements); @@ -29573,9 +29677,8 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 103 /* ThisKeyword */ || expr.kind === 101 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && - ts.isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + ts.isOptionalChain(expr); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -29632,10 +29735,10 @@ var ts; return isNarrowableReference(expr); } function createBranchLabel() { - return { flags: 4 /* BranchLabel */, antecedents: undefined }; + return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); } function createLoopLabel() { - return { flags: 8 /* LoopLabel */, antecedents: undefined }; + return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined }); } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag @@ -29654,36 +29757,32 @@ var ts; if (!expression) { return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - if (!ts.isOptionalChainRoot(expression.parent)) { - return unreachableFlow; - } + if ((expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) && + !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) { + return unreachableFlow; } if (!isNarrowingExpression(expression)) { return antecedent; } setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: flags, antecedent: antecedent, node: expression }); + return initFlowNode({ flags: flags, antecedent: antecedent, node: expression }); } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { - return antecedent; - } setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd }); + return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd }); } - function createFlowAssignment(antecedent, node) { + function createFlowMutation(flags, antecedent, node) { setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 16 /* Assignment */, antecedent: antecedent, node: node }); + var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node }); + if (currentExceptionTarget) { + addAntecedent(currentExceptionTarget, result); + } + return result; } function createFlowCall(antecedent, node) { setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 512 /* Call */, antecedent: antecedent, node: node }); - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }); + return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node }); } function finishFlowLabel(flow) { var antecedents = flow.antecedents; @@ -29743,7 +29842,7 @@ var ts; } function bindCondition(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); - if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && isOutermostOptionalChain(node))) { + if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -29874,87 +29973,56 @@ var ts; } function bindTryStatement(node) { var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - var tryPriors = []; - var oldFlowNodeCreated = flowNodeCreated; - // We hook the creation of all flow nodes within the `try` scope and store them so we can add _all_ of them - // as possible antecedents of the start of the `catch` or `finally` blocks. - // Don't bother intercepting the call if there's no finally or catch block that needs the information - if (node.catchClause || node.finallyBlock) { - flowNodeCreated = function (node) { return (tryPriors.push(node), node); }; - } + // We conservatively assume that *any* code in the try block can cause an exception, but we only need + // to track code that causes mutations (because only mutations widen the possible control flow type of + // a variable). The currentExceptionTarget is the target label for control flows that result from + // exceptions. We add all mutation flow nodes as antecedents of this label such that we can analyze them + // as possible antecedents of the start of catch or finally blocks. Furthermore, we add the current + // control flow to represent exceptions that occur before any mutations. + var saveExceptionTarget = currentExceptionTarget; + currentExceptionTarget = createBranchLabel(); + addAntecedent(currentExceptionTarget, currentFlow); bind(node.tryBlock); - flowNodeCreated = oldFlowNodeCreated; addAntecedent(preFinallyLabel, currentFlow); var flowAfterTry = currentFlow; var flowAfterCatch = unreachableFlow; if (node.catchClause) { - currentFlow = preTryFlow; - if (tryPriors.length) { - var preCatchFlow = createBranchLabel(); - addAntecedent(preCatchFlow, currentFlow); - for (var _i = 0, tryPriors_1 = tryPriors; _i < tryPriors_1.length; _i++) { - var p = tryPriors_1[_i]; - addAntecedent(preCatchFlow, p); - } - currentFlow = finishFlowLabel(preCatchFlow); - } + // Start of catch clause is the target of exceptions from try block. + currentFlow = finishFlowLabel(currentExceptionTarget); + // The currentExceptionTarget now represents control flows from exceptions in the catch clause. + // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block + // acts like a second try block. + currentExceptionTarget = createBranchLabel(); + addAntecedent(currentExceptionTarget, currentFlow); bind(node.catchClause); addAntecedent(preFinallyLabel, currentFlow); flowAfterCatch = currentFlow; } + var exceptionTarget = finishFlowLabel(currentExceptionTarget); + currentExceptionTarget = saveExceptionTarget; if (node.finallyBlock) { - // We add the nodes within the `try` block to the `finally`'s antecedents if there's no catch block - // (If there is a `catch` block, it will have all these antecedents instead, and the `finally` will - // have the end of the `try` block and the end of the `catch` block) - var preFinallyPrior = preTryFlow; - if (!node.catchClause) { - if (tryPriors.length) { - var preFinallyFlow_1 = createBranchLabel(); - addAntecedent(preFinallyFlow_1, preTryFlow); - for (var _a = 0, tryPriors_2 = tryPriors; _a < tryPriors_2.length; _a++) { - var p = tryPriors_2[_a]; - addAntecedent(preFinallyFlow_1, p); - } - preFinallyPrior = finishFlowLabel(preFinallyFlow_1); - } - } - // in finally flow is combined from pre-try/flow from try/flow from catch - // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable - // also for finally blocks we inject two extra edges into the flow graph. - // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it - // second -> edge that represents post-finally flow. - // these edges are used in following scenario: - // let a; (1) - // try { a = someOperation(); (2)} - // finally { (3) console.log(a) } (4) - // (5) a - // flow graph for this case looks roughly like this (arrows show ): - // (1-pre-try-flow) <--.. <-- (2-post-try-flow) - // ^ ^ - // |*****(3-pre-finally-label) -----| - // ^ - // |-- ... <-- (4-post-finally-label) <--- (5) - // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account - // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) - // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable - // Simply speaking code inside finally block is treated as reachable as pre-try-flow - // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. - // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from - // final flows of these blocks without taking pre-try flow into account. - // - // extra edges that we inject allows to control this behavior - // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }; + // Possible ways control can reach the finally block: + // 1) Normal completion of try block of a try-finally or try-catch-finally + // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally + // 3) Exception in try block of a try-finally + // 4) Exception in catch block of a try-catch-finally + // When analyzing a control flow graph that starts inside a finally block we want to consider all + // four possibilities above. However, when analyzing a control flow graph that starts outside (past) + // the finally block, we only want to consider the first two (if we're past a finally block then it + // must have completed normally). To make this possible, we inject two extra nodes into the control + // flow graph: An after-finally with an antecedent of the control flow at the end of the finally + // block, and a pre-finally with an antecedent that represents all exceptional control flows. The + // 'lock' property of the pre-finally references the after-finally, and the after-finally has a + // boolean 'locked' property that we set to true when analyzing a control flow that contained the + // the after-finally node. When the lock associated with a pre-finally is locked, the antecedent of + // the pre-finally (i.e. the exceptional control flows) are skipped. + var preFinallyFlow = initFlowNode({ flags: 4096 /* PreFinally */, antecedent: exceptionTarget, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); - // if flow after finally is unreachable - keep it - // otherwise check if flows after try and after catch are unreachable - // if yes - convert current flow to unreachable - // i.e. - // try { return "1" } finally { console.log(1); } - // console.log(2); // this line should be unreachable even if flow falls out of finally block + // If the end of the finally block is reachable, but the end of the try and catch blocks are not, + // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should + // result in an unreachable current control flow. if (!(currentFlow.flags & 1 /* Unreachable */)) { if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow @@ -29963,7 +30031,7 @@ var ts; } } if (!(currentFlow.flags & 1 /* Unreachable */)) { - var afterFinallyFlow = flowNodeCreated({ flags: 8192 /* AfterFinally */, antecedent: currentFlow }); + var afterFinallyFlow = initFlowNode({ flags: 8192 /* AfterFinally */, antecedent: currentFlow }); preFinallyFlow.lock = afterFinallyFlow; currentFlow = afterFinallyFlow; } @@ -29997,6 +30065,7 @@ var ts; var savedSubtreeTransformFlags = subtreeTransformFlags; subtreeTransformFlags = 0; var clauses = node.clauses; + var isNarrowingSwitch = isNarrowingExpression(node.parent.expression); var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { var clauseStart = i; @@ -30005,14 +30074,14 @@ var ts; i++; } var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; @@ -30076,7 +30145,7 @@ var ts; } function bindAssignmentTargetFlow(node) { if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); + currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } else if (node.kind === 191 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { @@ -30157,7 +30226,7 @@ var ts; if (operator === 62 /* EqualsToken */ && node.left.kind === 194 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } } @@ -30193,7 +30262,7 @@ var ts; } } else { - currentFlow = createFlowAssignment(currentFlow, node); + currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } } function bindVariableDeclarationFlow(node) { @@ -30215,12 +30284,9 @@ var ts; addDeclarationToSymbol(host.symbol, host, 32 /* Class */); } } - function isOutermostOptionalChain(node) { - return !ts.isOptionalChain(node.parent) || ts.isOptionalChainRoot(node.parent) || node !== node.parent.expression; - } function bindOptionalExpression(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); - if (!ts.isOptionalChain(node) || isOutermostOptionalChain(node)) { + if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -30258,7 +30324,7 @@ var ts; currentFlow = finishFlowLabel(preChainLabel); } doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget); - if (isOutermostOptionalChain(node)) { + if (ts.isOutermostOptionalChain(node)) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -30302,7 +30368,7 @@ var ts; if (node.expression.kind === 193 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } } @@ -30602,7 +30668,7 @@ var ts; var host = ts.getJSDocHost(typeAlias); container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); var declName = ts.getNameOfDeclaration(typeAlias); @@ -30615,7 +30681,12 @@ var ts; switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: - container = file; + if (!ts.isExternalOrCommonJsModule(file)) { + container = undefined; + } + else { + container = file; + } break; case 4 /* ThisProperty */: container = declName.parent.expression; @@ -30629,7 +30700,9 @@ var ts; case 0 /* None */: return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration"); } - declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + if (container) { + declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + } container = oldContainer; } } @@ -31025,6 +31098,8 @@ var ts; case 302 /* JSDocTypeLiteral */: case 185 /* MappedType */: return bindAnonymousTypeWorker(node); + case 307 /* JSDocClassTag */: + return bindJSDocClassTag(node); case 192 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); case 200 /* FunctionExpression */: @@ -31244,7 +31319,8 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -31260,7 +31336,7 @@ var ts; constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); } } - if (constructorSymbol) { + if (constructorSymbol && constructorSymbol.valueDeclaration) { // Declare a 'member' if the container is an ES5 class or ES6 constructor constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); // It's acceptable for multiple 'this' assignments of the same identifier to occur @@ -31333,6 +31409,10 @@ var ts; } function bindObjectDefinePrototypeProperty(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol) { + // Ensure the namespace symbol becomes class-like + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** @@ -31407,7 +31487,7 @@ var ts; } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); } return namespaceSymbol; @@ -32056,7 +32136,8 @@ var ts; || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type - || !node.body) { + || !node.body + || node.questionToken) { transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax @@ -32093,7 +32174,7 @@ var ts; function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 1048576 /* ContainsClassFields */; // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax. - if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type) { + if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken) { transformFlags |= 1 /* AssertTypeScript */; } // Hoisted variables related to class properties should live within the TypeScript class wrapper. @@ -32898,6 +32979,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 7] = "ResolvedTypeArguments"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -32908,12 +32990,6 @@ var ts; CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; })(CheckMode || (CheckMode = {})); - var ContextFlags; - (function (ContextFlags) { - ContextFlags[ContextFlags["None"] = 0] = "None"; - ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; - ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; - })(ContextFlags || (ContextFlags = {})); var AccessFlags; (function (AccessFlags) { AccessFlags[AccessFlags["None"] = 0] = "None"; @@ -33047,14 +33123,12 @@ var ts; undefinedSymbol.declarations = []; var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); globalThisSymbol.exports = globals; + globalThisSymbol.declarations = []; globals.set(globalThisSymbol.escapedName, globalThisSymbol); var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; - // This object is reused for `checkOptionalExpression` return values to avoid frequent GC due to nursery object allocations. - // This object represents a pool-size of 1. - var pooledOptionalTypeResult = { isOptional: false, type: undefined }; // for public members that accept a Node or one of its subtypes, we must guard against // synthetic nodes created during transformations by calling `getParseTreeNode`. // for most of these, we perform the guard only on `checker` to avoid any possible @@ -33173,9 +33247,9 @@ var ts; }, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (nodeIn) { + getContextualType: function (nodeIn, contextFlags) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); @@ -33224,7 +33298,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments), getAmbientModules: getAmbientModules, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { @@ -33353,10 +33427,10 @@ var ts; var errorType = createIntrinsicType(1 /* Any */, "error"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 262144 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 262144 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -33382,7 +33456,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", 1048576 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -33400,7 +33474,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 |= 1048576 /* NonInferrableType */; + anyFunctionType.objectFlags |= 2097152 /* 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); @@ -33409,10 +33483,10 @@ var ts; markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances var noIterationTypes = { @@ -33565,7 +33639,7 @@ var ts; var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } } } @@ -33575,7 +33649,7 @@ var ts; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -35053,7 +35127,7 @@ var ts; var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0); var symbol; if (name.kind === 75 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { @@ -35165,7 +35239,12 @@ var ts; return undefined; } var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl); - return init && getSymbolOfNode(init) || undefined; + if (init) { + var initSymbol = getSymbolOfNode(init); + if (initSymbol) { + return mergeJSSymbols(initSymbol, symbol); + } + } } function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); @@ -35592,8 +35671,8 @@ var ts; } function findConstructorDeclaration(node) { var members = node.members; - for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { - var member = members_2[_i]; + for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { + var member = members_3[_i]; if (member.kind === 161 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } @@ -36016,7 +36095,7 @@ var ts; // Type Reference or TypeAlias entity = Identifier meaning = 788968 /* Type */; } - var firstIdentifier = getFirstIdentifier(entityName); + var firstIdentifier = ts.getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { @@ -36508,8 +36587,6 @@ var ts; else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && ts.isClassLike(type.symbol.valueDeclaration) && - // Use `import` types for refs to other scopes, only anonymize something defined in the same scope - ts.findAncestor(type.symbol.valueDeclaration, function (d) { return d === ts.getSourceFileOfNode(context.enclosingDeclaration); }) && !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } @@ -36670,9 +36747,9 @@ var ts; } } } - var propertyName = symbolToName(propertySymbol, context, 111551 /* Value */, /*expectsIdentifier*/ true); - context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; + var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */); @@ -36871,7 +36948,7 @@ var ts; if (!context.tracker.trackSymbol) return; // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(accessExpression); + var firstIdentifier = ts.getFirstIdentifier(accessExpression); var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */); @@ -37237,22 +37314,34 @@ var ts; } } } + function isSingleQuotedStringNamed(d) { + var name = ts.getNameOfDeclaration(d); + if (name && ts.isStringLiteral(name) && (name.singleQuote || + (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")))) { + return true; + } + return false; + } function getPropertyNameNodeForSymbol(symbol, context) { - var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context); + var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed); + var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote); if (fromNameType) { return fromNameType; } + if (ts.isKnownSymbol(symbol)) { + return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3))); + } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); - return createPropertyNameNodeForIdentifierOrLiteral(rawName); + return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote); } // See getNameForSymbolFromNameType for a stringy equivalent - function getPropertyNameNodeForSymbolFromNameType(symbol, context) { + function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) { var nameType = symbol.nameType; if (nameType) { if (nameType.flags & 384 /* StringOrNumberLiteral */) { var name = "" + nameType.value; if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { - return ts.createLiteral(name); + return ts.createLiteral(name, !!singleQuote); } if (isNumericLiteralName(name) && ts.startsWith(name, "-")) { return ts.createComputedPropertyName(ts.createLiteral(+name)); @@ -37264,8 +37353,8 @@ var ts; } } } - function createPropertyNameNodeForIdentifierOrLiteral(name) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name); + function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -37305,7 +37394,7 @@ var ts; var visitedSymbols = ts.createMap(); var deferredPrivates; var oldcontext = context; - context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.mapMap(symbolTable, function (_symbol, name) { return [ts.unescapeLeadingUnderscores(name), true]; }), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { + context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it @@ -37323,6 +37412,10 @@ var ts; context.usedSymbolNames.set(name, true); }); } + ts.forEachEntry(symbolTable, function (symbol, name) { + var baseName = ts.unescapeLeadingUnderscores(name); + void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames` + }); var addingDeclare = !bundled; var exportEquals = symbolTable.get("export=" /* ExportEquals */); if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) { @@ -37514,7 +37607,11 @@ var ts; isPrivate = true; } var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0); - if (symbol.flags & 16 /* Function */) { + var isConstMergedWithNS = symbol.flags & 1536 /* Module */ && + symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && + symbol.escapedName !== "export=" /* ExportEquals */; + var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol); + if (symbol.flags & 16 /* Function */ || isConstMergedWithNSPrintableAsSignatureMerge) { serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } if (symbol.flags & 524288 /* TypeAlias */) { @@ -37525,7 +37622,8 @@ var ts; if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) - && !(symbol.flags & 32 /* Class */)) { + && !(symbol.flags & 32 /* Class */) + && !isConstMergedWithNSPrintableAsSignatureMerge) { serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags); } if (symbol.flags & 384 /* Enum */) { @@ -37542,7 +37640,7 @@ var ts; serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } } - if (symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */)) { + if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) { serializeModule(symbol, symbolName, modifierFlags); } if (symbol.flags & 64 /* Interface */) { @@ -37570,7 +37668,10 @@ var ts; } } function includePrivateSymbol(symbol) { + if (ts.some(symbol.declarations, ts.isParameterDeclaration)) + return; ts.Debug.assertDefined(deferredPrivates); + getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol deferredPrivates.set("" + getSymbolId(symbol), symbol); } function isExportingScope(enclosingDeclaration) { @@ -37629,8 +37730,14 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } + function getNamespaceMembersForSerialization(symbol) { + return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + } + function isTypeOnlyNamespace(symbol) { + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); }); + } function serializeModule(symbol, symbolName, modifierFlags) { - var members = !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + var members = getNamespaceMembersForSerialization(symbol); // Split NS members up by declaration - members whose parent symbol is the ns symbol vs those whose is not (but were added in later via merging) var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; }); var realMembers = locationMap.get("real") || ts.emptyArray; @@ -37640,17 +37747,20 @@ var ts; // so we don't even have placeholders to fill in. if (ts.length(realMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, /*suppressNewPrivateContext*/ false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); } if (ts.length(mergedMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - ts.forEach(mergedMembers, includePrivateSymbol); var nsBody = ts.createModuleBlock([ts.createExportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); - return ts.createExportSpecifier(name === localName ? undefined : localName, name); + var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); + includePrivateSymbol(target || s); + var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; + return ts.createExportSpecifier(name === targetName ? undefined : targetName, name); })))]); addResult(ts.createModuleDeclaration( /*decorators*/ undefined, @@ -37851,7 +37961,11 @@ var ts; case 254 /* ImportClause */: addResult(ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), + // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned + // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag + // In such cases, the `target` refers to the module itself already + ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 255 /* NamespaceImport */: addResult(ts.createImportDeclaration( @@ -37863,7 +37977,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([ ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName)) - ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 261 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, @@ -37877,6 +37991,7 @@ var ts; serializeMaybeAliasAssignment(symbol); break; case 208 /* BinaryExpression */: + case 193 /* PropertyAccessExpression */: // Could be best encoded as though an export specifier or as though an export assignment // If name is default or export=, do an export assignment // Otherwise do an export specifier @@ -37887,10 +38002,6 @@ var ts; serializeExportSpecifier(localName, targetName); } break; - case 193 /* PropertyAccessExpression */: - // A PAE alias is _always_ going to exist as an append to a top-level export, where our top level - // handling should always be sufficient to encode the export action itself - break; default: return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!"); } @@ -37914,7 +38025,8 @@ var ts; var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol); // serialize what the alias points to, preserve the declaration's initializer var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); - if (target) { + // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const + if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) { // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it // eg, `namespace A { export class B {} }; exports = A.B;` // Technically, this is all that's required in the case where the assignment is an entity name expression @@ -37989,6 +38101,7 @@ var ts; return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) && !getIndexInfoOfType(typeToSerialize, 0 /* String */) && !getIndexInfoOfType(typeToSerialize, 1 /* Number */) && + !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK !getDeclarationWithTypeAnnotation(hostSymbol) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && @@ -38132,7 +38245,7 @@ var ts; return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = getFirstIdentifier(node); + var leftmost = ts.getFirstIdentifier(node); var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); if (sym) { includePrivateSymbol(sym); @@ -38262,11 +38375,8 @@ var ts; return context.remappedSymbolNames.get("" + getSymbolId(symbol)); } } - if (input === "default" /* Default */) { - input = "_default"; - } - else if (input === "export=" /* ExportEquals */) { - input = "_exports"; + if (symbol) { + input = getNameCandidateWorker(symbol, input); } var i = 0; var original = input; @@ -38280,17 +38390,28 @@ var ts; } return input; } - function getInternalSymbolName(symbol, localName) { - if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) { - return context.remappedSymbolNames.get("" + getSymbolId(symbol)); - } + function getNameCandidateWorker(symbol, localName) { if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) { var flags = context.flags; context.flags |= 16777216 /* InInitialEntityName */; var nameCandidate = getNameOfSymbolAsWritten(symbol, context); context.flags = flags; - localName = ts.isIdentifierText(nameCandidate, languageVersion) && !ts.isStringANonContextualKeyword(nameCandidate) ? nameCandidate : getUnusedName("_default", symbol); + localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate; } + if (localName === "default" /* Default */) { + localName = "_default"; + } + else if (localName === "export=" /* ExportEquals */) { + localName = "_exports"; + } + localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_"); + return localName; + } + function getInternalSymbolName(symbol, localName) { + if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) { + return context.remappedSymbolNames.get("" + getSymbolId(symbol)); + } + localName = getNameCandidateWorker(symbol, localName); // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up context.remappedSymbolNames.set("" + getSymbolId(symbol), localName); return localName; @@ -38555,7 +38676,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); + var firstIdentifier = ts.getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); var id = importSymbol && "" + getSymbolId(importSymbol); if (importSymbol && !visited.has(id)) { @@ -38619,6 +38740,8 @@ var ts; return !!target.immediateBaseConstraint; case 6 /* JSDocTypeReference */: return !!getSymbolLinks(target).resolvedJSDocType; + case 7 /* ResolvedTypeArguments */: + return !!target.resolvedTypeArguments; } return ts.Debug.assertNever(propertyName); } @@ -38704,7 +38827,9 @@ var ts; } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); - return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + result.objectFlags |= 131072 /* ObjectRestType */; + return result; } // Determine the control flow type associated with a destructuring declaration or assignment. The following // forms of destructuring are possible: @@ -39090,23 +39215,23 @@ var ts; kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); - var members_3 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_3); + var members_4 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_3.has(name)) { + if (members_4.has(name)) { var exportedMember = exportedType_1.members.get(name); var union = createSymbol(s.flags | exportedMember.flags, name); union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_3.set(name, union); + members_4.set(name, union); } else { - members_3.set(name, s); + members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag return result; } @@ -39166,7 +39291,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -39306,16 +39431,12 @@ var ts; if (!declaration.statements.length) { return emptyObjectType; } - var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); - if (type_1.flags & 524288 /* Object */) { - return getRegularTypeOfObjectLiteral(type_1); - } - return type_1; + return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression))); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39383,7 +39504,7 @@ var ts; } if (!popTypeResolution()) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39466,7 +39587,9 @@ var ts; } else { ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -39512,11 +39635,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_2; + return type_1; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -39702,6 +39825,7 @@ var ts; // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 245 /* InterfaceDeclaration */); + ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -39732,7 +39856,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length === 1) { var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -40439,8 +40563,8 @@ var ts; var decl = _a[_i]; var members = ts.getMembersOfDeclaration(decl); if (members) { - for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { - var member = members_4[_b]; + for (var _b = 0, members_5 = members; _b < members_5.length; _b++) { + var member = members_5[_b]; if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { lateBindMember(symbol, earlySymbols, lateSymbols, member); } @@ -40569,8 +40693,8 @@ var ts; var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + var sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -40578,15 +40702,13 @@ var ts; sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; } function cloneSignature(sig) { var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -40598,13 +40720,25 @@ var ts; result.mapper = undefined; return result; } - function createOptionalCallSignature(signature) { + function getOptionalCallSignature(signature, callChainFlags) { + if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) { + return signature; + } + if (!signature.optionalCallSignatureCache) { + signature.optionalCallSignatureCache = {}; + } + var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer"; + return signature.optionalCallSignatureCache[key] + || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags)); + } + function createOptionalCallSignature(signature, callChainFlags) { + ts.Debug.assert(callChainFlags === 4 /* IsInnerCallChain */ || callChainFlags === 8 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both."); var result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= callChainFlags; return result; } function getExpandedParameters(sig) { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { var restIndex_1 = sig.parameters.length - 1; var restParameter = sig.parameters[restIndex_1]; var restType = getTypeOfSymbol(restParameter); @@ -40629,7 +40763,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJSFile(baseTypeNode); @@ -40793,11 +40927,9 @@ var ts; var params = combineUnionParameters(left, right); var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - var hasRestParam = left.hasRestParameter || right.hasRestParameter; - var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */); result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); return result; } @@ -40970,7 +41102,7 @@ var ts; var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray; if (symbol.flags & 16 /* Function */) { constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) : undefined; })); } if (!constructSignatures.length) { @@ -41476,8 +41608,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_3 = types_6[_i]; - var baseType = getBaseConstraint(type_3); + var type_2 = types_6[_i]; + var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } @@ -41910,7 +42042,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var flags = 0 /* None */; var minArgumentCount = 0; var thisParameter = void 0; var hasThisParameter = false; @@ -41941,7 +42073,7 @@ var ts; parameters.push(paramSymbol); } if (type && type.kind === 186 /* LiteralType */) { - hasLiteralTypes = true; + flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || @@ -41967,9 +42099,11 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1 /* HasRestParameter */; + } links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, - /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -42112,8 +42246,11 @@ var ts; signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, /*wasOptional*/ true); + if (signature.flags & 4 /* IsInnerCallChain */) { + type = addOptionalTypeMarker(type); + } + else if (signature.flags & 8 /* IsOuterCallChain */) { + type = getOptionalType(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -42169,7 +42306,7 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, 1 /* Number */); @@ -42386,7 +42523,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 1835008 /* PropagatingFlags */; + return result & 3670016 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -42420,13 +42557,25 @@ var ts; return type; } function getTypeArguments(type) { + var _a, _b; if (!type.resolvedTypeArguments) { + if (!pushTypeResolution(type, 7 /* ResolvedTypeArguments */)) { + return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray; + } var node = type.node; var typeArguments = !node ? ts.emptyArray : node.kind === 168 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : node.kind === 173 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode); - type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + if (popTypeResolution()) { + type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + } + else { + type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray; + error(type.node || currentNode, type.target.symbol + ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves + : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol)); + } } return type.resolvedTypeArguments; } @@ -42543,7 +42692,7 @@ var ts; errorType; } if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) { - var jsdocType = getTypeFromJSAlias(node, symbol); + var jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -42556,18 +42705,30 @@ var ts; return errorType; } /** - * A JSdoc TypeReference may be to a value imported from commonjs. - * These should really be aliases, but this special-case code fakes alias resolution - * by producing a type from a value. + * A JSdoc TypeReference may be to a value, but resolve it as a type anyway. + * Note: If the value is imported from commonjs, it should really be an alias, + * but this function's special-case code fakes alias resolution as well. */ - function getTypeFromJSAlias(node, symbol) { + function getTypeFromJSDocValueReference(node, symbol) { var valueType = getTypeOfSymbol(symbol); - var typeType = valueType.symbol && - valueType.symbol !== symbol && // Make sure this is a commonjs export by checking that symbol -> type -> symbol doesn't roundtrip. - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + var typeType = valueType; + if (symbol.valueDeclaration) { + var decl = ts.getRootDeclaration(symbol.valueDeclaration); + var isRequireAlias = false; + if (ts.isVariableDeclaration(decl) && decl.initializer) { + var expr = decl.initializer; + // skip past entity names, eg `require("x").a.b.c` + while (ts.isPropertyAccessExpression(expr)) { + expr = expr.expression; + } + isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol; + } + var isImportTypeWithQualifier = node.kind === 187 /* ImportType */ && node.qualifier; + if (isRequireAlias || isImportTypeWithQualifier) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable, substitute) { if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === typeVariable) { @@ -42996,7 +43157,7 @@ var ts; if (type === wildcardType) includes |= 4194304 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 262144 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) includes |= 2097152 /* IncludesNonWideningType */; } else { @@ -43123,7 +43284,7 @@ var ts; neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 131072 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -43273,7 +43434,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) & 131072 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -43282,7 +43443,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 131072 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -43311,7 +43472,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 131072 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -44108,7 +44269,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host)) { + while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 137 /* ReadonlyKeyword */) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -44209,7 +44370,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ @@ -44523,7 +44684,7 @@ var ts; // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */); result.target = signature; result.mapper = mapper; return result; @@ -45404,20 +45565,20 @@ var ts; } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, - /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */; } /** * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any` */ function isAnySignature(s) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } /** * See signatureRelatedTo, compareSignaturesIdentical */ - function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) { // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; @@ -45436,6 +45597,9 @@ var ts; var sourceCount = getParameterCount(source); var sourceRestType = getNonArrayRestType(source); var targetRestType = getNonArrayRestType(target); + if (sourceRestType || targetRestType) { + void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers); + } if (sourceRestType && targetRestType && sourceCount !== targetCount) { // We're not able to relate misaligned complex rest parameters return 0 /* False */; @@ -45479,7 +45643,7 @@ var ts; (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); var related = callbacks ? // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is - compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) : + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { @@ -45493,13 +45657,13 @@ var ts; // If a signature resolution is already in-flight, skip issuing a circularity error // here and just use the `any` type directly var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType - : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(target.declaration.symbol) + : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol)) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType - : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(source.declaration.symbol) + : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol)) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); @@ -45686,7 +45850,7 @@ var ts; return true; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var related = relation.get(getRelationKey(source, target, relation)); + var related = relation.get(getRelationKey(source, target, /*isIntersectionConstituent*/ false, relation)); if (related !== undefined) { return !!(related & 1 /* Succeeded */); } @@ -46057,7 +46221,7 @@ var ts; // and we need to handle "each" relations before "some" relations for the same kind of type. if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), isIntersectionConstituent) : + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); } else { @@ -46095,7 +46259,7 @@ var ts; // // - For a primitive type or type parameter (such as 'number = A & B') there is no point in // breaking the intersection apart. - result = someTypeRelatedToType(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ true); + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { @@ -46208,7 +46372,7 @@ var ts; // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) - if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration)) { + if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) { // Note that extraneous children (as in `extra`) don't pass this check, // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute. errorNode = prop.valueDeclaration.name; @@ -46219,7 +46383,7 @@ var ts; // use the property's value declaration if the property is assigned inside the literal itself var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; - if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) { var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; @@ -46379,14 +46543,14 @@ var ts; } return result; } - function someTypeRelatedToType(source, target, reportErrors, isIntersectionConstituent) { + function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; for (var i = 0; i < len; i++) { - var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, isIntersectionConstituent); + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { return related; } @@ -46474,7 +46638,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, relation); + var id = getRelationKey(source, target, isIntersectionConstituent, relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -47368,7 +47532,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, incompatibleReporter, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, incompatibleReporter, isRelatedTo, reportUnreliableMarkers); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -47660,17 +47824,18 @@ var ts; * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. * For other cases, the types ids are used. */ - function getRelationKey(source, target, relation) { + function getRelationKey(source, target, isIntersectionConstituent, relation) { if (relation === identityRelation && source.id > target.id) { var temp = source; source = target; target = temp; } + var intersection = isIntersectionConstituent ? "&" : ""; if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { var typeParameters = []; - return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + intersection; } - return source.id + "," + target.id; + return source.id + "," + target.id + intersection; } // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. @@ -47721,7 +47886,7 @@ var ts; // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`). function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 524288 /* Object */) { + if (depth >= 5 && type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { var symbol = type.symbol; if (symbol) { var count = 0; @@ -48096,37 +48261,19 @@ var ts; function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type) { + return type !== optionalType; + } function removeOptionalTypeMarker(type) { - return strictNullChecks ? filterType(type, function (t) { return t !== optionalType; }) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } - function propagateOptionalTypeMarker(type, wasOptional) { - return wasOptional ? addOptionalTypeMarker(type) : type; + function propagateOptionalTypeMarker(type, node, wasOptional) { + return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional, type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - function checkOptionalExpression(parent, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var isOptional = false; - var type = checkExpression(expression); - if (ts.isOptionalChain(parent)) { - if (parent.questionDotToken) { - // If we have a questionDotToken then we are an OptionalExpression and should remove `null` and - // `undefined` from the type and add the optionalType to the result, if needed. - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - // If we do not have a questionDotToken, then we are an OptionalChain and we remove the optionalType and - // indicate whether we need to add optionalType back into the result. - var nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType, expression) { + return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } /** * Is source potentially coercible to target type under `==`. @@ -48280,14 +48427,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 */ | 1048576 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* 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) & 786432 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -48332,7 +48479,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 262144 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -48358,7 +48505,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) & 262144 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -48438,7 +48585,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 262144 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -48555,7 +48702,7 @@ var ts; return !!(type.flags & 63176704 /* Instantiable */ || 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 */ || + objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { @@ -48610,7 +48757,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) & 1048576 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }); } function createReverseMappedType(source, target, constraint) { @@ -48761,10 +48908,7 @@ var ts; // inferring a type parameter constraint. Instead, make a lower priority inference from // the full source to whatever remains in the target. For example, when inferring from // string to 'string | T', make a lower priority inference of string for T. - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, 1 /* NakedTypeVariable */); return; } source = getUnionType(sources); @@ -48797,7 +48941,7 @@ 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) & 1048576 /* NonInferrableType */ || source === silentNeverType || (priority & 16 /* ReturnType */ && (source === autoType || source === autoArrayType))) { + if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === silentNeverType || (priority & 16 /* ReturnType */ && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -48864,10 +49008,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - var savePriority = priority; - priority |= 32 /* LiteralKeyof */; - inferFromTypes(empty, target.type); - priority = savePriority; + inferWithPriority(empty, target.type, 32 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -48919,6 +49060,12 @@ var ts; } } } + function inferWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -48984,6 +49131,18 @@ var ts; } return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types) { + var typeVariable; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var type = types_13[_i]; + var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } function inferToMultipleTypes(source, targets, targetFlags) { var typeVariableCount = 0; if (targetFlags & 1048576 /* Union */) { @@ -49013,6 +49172,16 @@ var ts; } } } + if (typeVariableCount === 0) { + // If every target is an intersection of types containing a single naked type variable, + // make a lower priority inference to that type variable. This handles inferring from + // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T. + var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */); + } + return; + } // If the target has a single naked type variable and no inference circularities were // encountered above (meaning we explored the types fully), create a union of the source // types from which no inferences have been made so far and infer from that union to the @@ -49044,15 +49213,12 @@ var ts; // we want to infer string for T, not Promise | string. For intersection types // we only infer to single naked type variables. if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) { - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) { var t = targets_4[_b]; if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, 1 /* NakedTypeVariable */); } } - priority = savePriority; } } function inferToMappedType(source, target, constraintType) { @@ -49073,14 +49239,12 @@ var ts; if (inference && !inference.isFixed) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - var savePriority = priority; // 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). - priority |= ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? - 4 /* PartialHomomorphicMappedType */ : 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? + 4 /* PartialHomomorphicMappedType */ : + 2 /* HomomorphicMappedType */); } } return true; @@ -49088,10 +49252,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. - var savePriority = priority; - priority |= 8 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, 8 /* 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 @@ -49200,7 +49361,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 1048576 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -49469,6 +49630,15 @@ var ts; } return false; } + function optionalChainContainsReference(source, target) { + while (ts.isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property // a possible discriminant if its type differs in the constituents of containing union type, and if every @@ -49589,8 +49759,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; result |= getTypeFacts(t); } return result; @@ -49959,8 +50129,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -50041,9 +50211,18 @@ var ts; // expressions are potential type predicate function calls. In order to avoid triggering // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. - var funcType = node.parent.kind === 225 /* ExpressionStatement */ ? getTypeOfDottedName(node.expression, /*diagnostic*/ undefined) : - node.expression.kind !== 101 /* SuperKeyword */ ? checkOptionalExpression(node, node.expression).type : - undefined; + var funcType = void 0; + if (node.parent.kind === 225 /* ExpressionStatement */) { + funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); + } + else if (node.expression.kind !== 101 /* SuperKeyword */) { + if (ts.isOptionalChain(node)) { + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */); var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -50056,6 +50235,13 @@ var ts; return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */); } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { + return callExpression.arguments[predicate.parameterIndex]; + } + var invokedExpression = ts.skipParentheses(callExpression.expression); + return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined; + } function reportFlowControlError(node) { var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); var sourceFile = ts.getSourceFileOfNode(node); @@ -50071,6 +50257,11 @@ var ts; function isUnlockedReachableFlowNode(flow) { return !(flow.flags & 4096 /* PreFinally */ && flow.lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); } + function isFalseExpression(expr) { + var node = ts.skipParentheses(expr); + return node.kind === 90 /* FalseKeyword */ || node.kind === 208 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); + } function isReachableFlowNodeWorker(flow, noCacheCheck) { while (true) { if (flow === lastFlowNode) { @@ -50090,8 +50281,17 @@ var ts; } else if (flags & 512 /* Call */) { var signature = getEffectsSignature(flow.node); - if (signature && getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { - return false; + if (signature) { + var predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3 /* AssertsIdentifier */) { + var predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { + return false; + } } flow = flow.antecedent; } @@ -50325,6 +50525,9 @@ var ts; } function narrowTypeByAssertion(type, expr) { var node = ts.skipParentheses(expr); + if (node.kind === 90 /* FalseKeyword */) { + return unreachableNeverType; + } if (node.kind === 208 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); @@ -50343,7 +50546,7 @@ var ts; var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : - predicate.kind === 3 /* AssertsIdentifier */ ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -50414,17 +50617,24 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } else if (expr.kind === 203 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); + } + else if (expr.kind === 203 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -50432,6 +50642,7 @@ var ts; var antecedentTypes = []; var subtypeReduction = false; var seenIncomplete = false; + var bypassFlow; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; if (antecedent.flags & 4096 /* PreFinally */ && antecedent.lock.locked) { @@ -50440,6 +50651,11 @@ var ts; // in this case we should ignore this branch. continue; } + if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) { + // The antecedent is the bypass branch of a potentially exhaustive switch statement. + bypassFlow = antecedent; + continue; + } var flowType = getTypeAtFlowNode(antecedent); var type = getTypeFromFlowType(flowType); // If the type at a particular antecedent path is the declared type and the @@ -50460,6 +50676,25 @@ var ts; seenIncomplete = true; } } + if (bypassFlow) { + var flowType = getTypeAtFlowNode(bypassFlow); + var type = getTypeFromFlowType(flowType); + // If the bypass flow contributes a type we haven't seen yet and the switch statement + // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase + // the risk of circularities, we only want to perform them when they make a difference. + if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) { + if (type === declaredType && declaredType === initialType) { + return type; + } + antecedentTypes.push(type); + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + } return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { @@ -50566,6 +50801,9 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } @@ -50614,6 +50852,14 @@ var ts; if (isMatchingReference(reference, right_1)) { return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + } + else if (optionalChainContainsReference(right_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left_1, declaredType)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } @@ -50637,6 +50883,15 @@ var ts; } return type; } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + // We are in a branch of obj?.foo === value or obj?.foo !== value. We remove undefined and null from + // the type of obj if (a) the operator is === and the type of value doesn't include undefined or (b) the + // operator is !== and the type of value is undefined. + var effectiveTrue = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */ ? assumeTrue : !assumeTrue; + var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */; + var valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? 262144 /* EQUndefinedOrNull */ : 65536 /* EQUndefined */)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* Any */) { return type; @@ -50684,8 +50939,14 @@ var ts; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands + if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, target)) { @@ -50693,9 +50954,6 @@ var ts; } return type; } - if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } @@ -50728,6 +50986,10 @@ var ts; return type; } } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { + var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify // values with unit types, except for the case where @@ -50860,6 +51122,9 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' // references might reference a different 'y' property. However, we make an exception @@ -50932,39 +51197,28 @@ var ts; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + var predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (ts.isAccessExpression(invokedExpression) && predicate.type) { - var possibleReference = ts.skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if (ts.isOptionalChainRoot(expr.parent) || + if (ts.isExpressionOfOptionalChainRoot(expr) || ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -51245,7 +51499,24 @@ var ts; } } else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { - error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + var diag = error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // See GH:32846 - if the user is using a variable whose type is () => T1 | ... | undefined + // they may have meant to specify the type as (() => T1 | ...) | undefined + // This is assumed if: the type is a FunctionType, the return type is a Union, the last constituent of + // the union is `undefined` + if (type.symbol && type.symbol.declarations.length === 1 && ts.isFunctionTypeNode(type.symbol.declarations[0])) { + var funcTypeNode = type.symbol.declarations[0]; + var returnType = getReturnTypeFromAnnotation(funcTypeNode); + if (returnType && returnType.flags & 1048576 /* Union */) { + var unionTypes_3 = funcTypeNode.type.types; + if (unionTypes_3 && unionTypes_3[unionTypes_3.length - 1].kind === 145 /* UndefinedKeyword */) { + var parenedFuncType = ts.getMutableClone(funcTypeNode); + // Highlight to the end of the second to last constituent of the union + parenedFuncType.end = unionTypes_3[unionTypes_3.length - 2].end; + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(parenedFuncType, ts.Diagnostics.Did_you_mean_to_parenthesize_this_function_type)); + } + } + } // Return the declared type to reduce follow-on errors return type; } @@ -52025,18 +52296,22 @@ var ts; return undefined; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget, arg) { + function getContextualTypeForArgument(callTarget, arg, contextFlags) { var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + function getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & 4 /* Completion */ && signature.target) { + var baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { @@ -52395,7 +52670,7 @@ var ts; } /* falls through */ case 196 /* NewExpression */: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case 198 /* TypeAssertionExpression */: case 216 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); @@ -52610,8 +52885,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -52712,7 +52987,7 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; } return literalType; } @@ -52849,7 +53124,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 1835008 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -52958,7 +53233,7 @@ 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 */ | 524288 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { result.objectFlags |= 16384 /* JSLiteral */; } @@ -53056,7 +53331,7 @@ var ts; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 1835008 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -53136,7 +53411,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 */ | 524288 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -53608,8 +53883,8 @@ var ts; function symbolHasNonMethodDeclaration(symbol) { return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } - function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */); @@ -53617,22 +53892,34 @@ var ts; function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + function reportObjectPossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + } + function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? - (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + reportError(node, kind); var t = getNonNullableType(type); return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) { @@ -53641,10 +53928,16 @@ var ts; return nonNullType; } function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + function checkPropertyAccessChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); } function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node) { while (node.parent.kind === 199 /* ParenthesizedExpression */) { @@ -53652,8 +53945,7 @@ var ts; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var _a = checkOptionalExpression(node, left), isOptional = _a.isOptional, leftType = _a.type; + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -53706,7 +53998,7 @@ var ts; } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { // Only compute control flow type if this is a property access expression that isn't an @@ -54028,7 +54320,15 @@ var ts; return false; } function checkIndexedAccess(node) { - var _a = checkOptionalExpression(node, node.expression), isOptional = _a.isOptional, exprType = _a.type; + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + function checkElementAccessChain(node) { + var exprType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -54044,7 +54344,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -54115,7 +54415,7 @@ var ts; // interface B extends A { (x: 'foo'): string } // const b: B; // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] - function reorderCandidates(signatures, result, isOptionalCall) { + function reorderCandidates(signatures, result, callChainFlags) { var lastParent; var lastSymbol; var cutoffIndex = 0; @@ -54145,7 +54445,7 @@ var ts; lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -54156,7 +54456,7 @@ var ts; else { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature); } } function isSpreadArgument(arg) { @@ -54240,7 +54540,7 @@ var ts; // the declared number of type parameters, the call has an incorrect arity. var numTypeParameters = ts.length(signature.typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - return !typeArguments || + return !ts.some(typeArguments) || (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. @@ -54451,7 +54751,19 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var thisArgumentType = void 0; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (ts.isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -54678,7 +54990,7 @@ var ts; 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.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_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 (min < argCount && argCount < max) { @@ -54734,7 +55046,7 @@ var ts; } return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } - function resolveCall(node, signatures, candidatesOutArray, checkMode, isOptionalCall, fallbackError) { + function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { var isTaggedTemplate = node.kind === 197 /* TaggedTemplateExpression */; var isDecorator = node.kind === 156 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -54749,7 +55061,7 @@ var ts; } var candidates = candidatesOutArray || []; // reorderCandidates fills up the candidates array directly - reorderCandidates(signatures, candidates, isOptionalCall); + reorderCandidates(signatures, candidates, callChainFlags); if (!candidates.length) { if (reportErrors) { diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); @@ -54911,7 +55223,7 @@ var ts; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) { @@ -54929,7 +55241,7 @@ var ts; var inferenceContext = void 0; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - if (typeArguments) { + if (ts.some(typeArguments)) { typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); if (!typeArgumentTypes) { candidateForTypeArgumentError = candidate; @@ -55004,34 +55316,34 @@ var ts; var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; var _loop_15 = function (i) { - var symbols = ts.mapDefined(candidates, function (_a) { - var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; - return hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : - i < parameters.length ? parameters[i] : undefined; - }); + var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined; }); ts.Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { _loop_15(i); } - var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); - var hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); + var flags = 0 /* None */; + if (restParameterSymbols.length !== 0) { var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1 /* HasRestParameter */; + } + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2 /* HasLiteralTypes */; } return createSignature(candidates[0].declaration, /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. thisParameter, parameters, /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), - /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, - /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + /*typePredicate*/ undefined, minArgumentCount, flags); } function getNumNonRestParameters(signature) { var numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); @@ -55107,12 +55419,24 @@ var ts; var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */); } } return resolveUntypedCall(node); } - var _b = checkOptionalExpression(node, node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined), isOptional = _b.isOptional, funcType = _b.type; + var callChainFlags; + var funcType = checkExpression(node.expression); + if (ts.isCallChain(node)) { + var nonOptionalType = getOptionalExpressionType(funcType, node.expression); + callChainFlags = nonOptionalType === funcType ? 0 /* None */ : + ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ : + 4 /* IsInnerCallChain */; + funcType = nonOptionalType; + } + else { + callChainFlags = 0 /* None */; + } + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -55178,7 +55502,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, isOptional); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags); } function isGenericFunctionReturningFunction(signature) { return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature))); @@ -55241,7 +55565,7 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */); } // If expressionType's apparent type is an object type with no construct signatures but // one or more call signatures, the expression is processed as a function call. A compile-time @@ -55249,7 +55573,7 @@ var ts; // operation is Any. It is an error to have a Void this type. var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); if (!noImplicitAny) { if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); @@ -55334,8 +55658,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var constituent = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var constituent = types_17[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -55426,7 +55750,7 @@ var ts; invocationError(node.tag, apparentType, 0 /* Call */); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); } /** * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. @@ -55479,7 +55803,7 @@ var ts; invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage); } function createSignatureForJSXIntrinsic(node, result) { var namespace = getJsxNamespaceAt(node); @@ -55494,9 +55818,7 @@ var ts; return createSignature(declaration, /*typeParameters*/ undefined, /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, - /*returnTypePredicate*/ undefined, 1, - /*hasRestparameter*/ false, - /*hasLiteralTypes*/ false); + /*returnTypePredicate*/ undefined, 1, 0 /* None */); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -55519,7 +55841,7 @@ var ts; error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); return resolveErrorCall(node); } - return resolveCall(node, signatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */); } /** * Sometimes, we have a decorator that could accept zero arguments, @@ -55529,7 +55851,7 @@ var ts; function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } @@ -55600,7 +55922,7 @@ var ts; return false; } function mergeJSSymbols(target, source) { - if (source && (ts.hasEntries(source.exports) || ts.hasEntries(source.members))) { + if (source) { var links = getSymbolLinks(source); if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) { var inferred = isTransientSymbol(target) ? target : cloneSymbol(target); @@ -55910,7 +56232,7 @@ var ts; return type; } function getParameterNameAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -55927,11 +56249,11 @@ var ts; return tryGetTypeAtPosition(signature, pos) || anyType; } function tryGetTypeAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // We want to return the value undefined for an out of bounds parameter position, // so we need to check bounds here before calling getIndexedAccessType (which // otherwise would return the type 'undefined'). @@ -55966,7 +56288,7 @@ var ts; } function getParameterCount(signature) { var length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -55975,7 +56297,7 @@ var ts; return length; } function getMinArgumentCount(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { var minLength = restType.target.minLength; @@ -55987,14 +56309,14 @@ var ts; return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } return false; } function getEffectiveRestType(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -56011,7 +56333,7 @@ var ts; return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, inferenceContext) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -56044,7 +56366,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } } - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56052,7 +56374,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56329,8 +56651,8 @@ var ts; var witnesses = getSwitchClauseTypeOfWitnesses(node); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_4 = getBaseConstraintOfType(operandType) || operandType; - return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + var type_3 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -56457,9 +56779,9 @@ var ts; return links.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + 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 |= 1048576 /* NonInferrableType */; + returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } return anyFunctionType; @@ -56688,8 +57010,7 @@ var ts; var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); var func = ts.getContainingFunction(node); - if (func && func.kind !== 161 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + if (func && func.kind !== 161 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -56790,8 +57111,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -57425,25 +57746,10 @@ var ts; } return [effectiveLeft, effectiveRight]; } - function isYieldExpressionInClass(node) { - var current = node; - var parent = node.parent; - while (parent) { - if (ts.isFunctionLike(parent) && current === parent.body) { - return false; - } - else if (ts.isClassLike(current)) { - return true; - } - current = parent; - parent = parent.parent; - } - return false; - } function checkYieldExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 8192 /* YieldContext */) || isYieldExpressionInClass(node)) { + if (!(node.flags & 8192 /* YieldContext */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -57779,6 +58085,18 @@ var ts; } } } + function getReturnTypeOfSingleNonGenericCallSignature(funcType) { + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) { + var funcType = checkExpression(expr.expression); + var nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType); + return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType); + } /** * Returns the type of an expression. Unlike checkExpression, this function is simply concerned * with computing the type and may not fully check all contained sub-expressions for errors. @@ -57790,10 +58108,10 @@ var ts; // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. if (ts.isCallExpression(expr) && expr.expression.kind !== 101 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { - var _a = checkOptionalExpression(expr, expr.expression), isOptional = _a.isOptional, funcType = _a.type; - var signature = getSingleCallSignature(funcType); - if (signature && !signature.typeParameters) { - return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); + var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : + getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression)); + if (type) { + return type; } } else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) { @@ -57843,7 +58161,7 @@ var ts; (node.parent.kind === 194 /* ElementAccessExpression */ && node.parent.expression === node) || ((node.kind === 75 /* Identifier */ || node.kind === 152 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || (node.parent.kind === 171 /* TypeQuery */ && node.parent.exprName === node)) || - (node.parent.kind === 261 /* ExportSpecifier */ && (compilerOptions.preserveConstEnums || node.flags & 8388608 /* Ambient */)); // We allow reexporting const enums + (node.parent.kind === 261 /* ExportSpecifier */); // We allow reexporting const enums if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -58047,7 +58365,7 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -59222,7 +59540,7 @@ var ts; return; } // Verify there is no local declaration that could collide with the promise constructor. - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); @@ -59279,7 +59597,7 @@ var ts; function markEntityNameOrEntityExpressionAsReference(typeName) { if (!typeName) return; - var rootName = getFirstIdentifier(typeName); + var rootName = ts.getFirstIdentifier(typeName); var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol @@ -59319,8 +59637,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var typeNode = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var typeNode = types_19[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -61095,10 +61413,7 @@ var ts; firstDefaultClause = clause; } else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -61119,6 +61434,9 @@ var ts; } } ts.forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -61641,11 +61959,13 @@ var ts; // same when the derived property is from an assignment continue; } - if (basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property; - } - else if (basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor; + var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */; + var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */; + if (overriddenInstanceProperty || overriddenInstanceAccessor) { + var errorMessage_1 = overriddenInstanceProperty ? + ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : + 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 { var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 158 /* PropertyDeclaration */ && !d.initializer; }); @@ -61661,24 +61981,22 @@ var ts; || !ts.isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { - var errorMessage_1 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; - error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType)); + var errorMessage_2 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType)); } } - // correct case - continue; } + // correct case + continue; } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { - // method is overridden with method -- correct case + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { + // method is overridden with method or property -- correct case continue; } - else if (derived.flags & 98304 /* Accessor */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & 98304 /* Accessor */) { @@ -62184,22 +62502,6 @@ var ts; break; } } - function getFirstIdentifier(node) { - switch (node.kind) { - case 75 /* Identifier */: - return node; - case 152 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 75 /* Identifier */); - return node; - case 193 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 75 /* Identifier */); - return node; - } - } function getFirstNonModuleExportsIdentifier(node) { switch (node.kind) { case 75 /* Identifier */: @@ -62329,7 +62631,7 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - var moduleName = getFirstIdentifier(node.moduleReference); + var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } @@ -62396,7 +62698,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -64702,10 +65004,10 @@ var ts; if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -65588,7 +65890,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -65658,6 +65960,14 @@ var ts; case 2 /* Next */: return "nextType"; } } + function signatureHasRestParameter(s) { + return !!(s.flags & 1 /* HasRestParameter */); + } + ts.signatureHasRestParameter = signatureHasRestParameter; + function signatureHasLiteralTypes(s) { + return !!(s.flags & 2 /* HasLiteralTypes */); + } + ts.signatureHasLiteralTypes = signatureHasLiteralTypes; })(ts || (ts = {})); var ts; (function (ts) { @@ -66591,7 +66901,9 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } // Because we are updating existed propertyAccess we want to inherit its emitFlags // instead of using the default from createPropertyAccess return node.expression !== expression @@ -66629,7 +66941,9 @@ var ts; } ts.createElementAccess = createElementAccess; function updateElementAccess(node, expression, argumentExpression) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -66663,7 +66977,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (ts.isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -67265,7 +67581,7 @@ var ts; var node = createSynthesizedNode(231 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -69791,7 +70107,7 @@ var ts; var conditionalPrecedence = ts.getOperatorPrecedence(209 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { return ts.createParen(condition); } return condition; @@ -70389,6 +70705,12 @@ var ts; * Gets the property name of a BindingOrAssignmentElement */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement); + ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element."); + return propertyName; + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { case 190 /* BindingElement */: // `a` in `let { a: b } = ...` @@ -70424,9 +70746,8 @@ var ts; ? target.expression : target; } - ts.Debug.fail("Invalid property name for binding element."); } - ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; function isStringOrNumericLiteral(node) { var kind = node.kind; return kind === 10 /* StringLiteral */ @@ -72445,7 +72766,8 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node)) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); @@ -72514,6 +72836,17 @@ var ts; } return false; } + function bindingOrAssignmentElementContainsNonLiteralComputedName(element) { + var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element); + if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) { + return true; + } + var target = ts.getTargetOfBindingOrAssignmentElement(element); + return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target); + } + function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) { + return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName); + } /** * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * @@ -72544,7 +72877,8 @@ var ts; }; if (ts.isVariableDeclaration(node)) { var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); - if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node))) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); @@ -73843,8 +74177,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { - var member = members_5[_i]; + for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { + var member = members_6[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -74234,8 +74568,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -74847,7 +75181,12 @@ var ts; * * @param node The module declaration node. */ - function shouldEmitModuleDeclaration(node) { + function shouldEmitModuleDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration); + if (!node) { + // If we can't find a parse tree node, assume the node is instantiated. + return true; + } return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } /** @@ -75666,7 +76005,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); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -77423,7 +77762,7 @@ var ts; } return ts.updateParen(node, expression); } - function visitNonOptionalPropertyAccessExpression(node, captureThisArg) { + function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg) { if (ts.isOptionalChain(node)) { // If `node` is an optional chain, then it is the outermost chain of an optional expression. return visitOptionalExpression(node, captureThisArg); @@ -77432,27 +77771,17 @@ var ts; ts.Debug.assertNotNode(expression, ts.isSyntheticReference); var thisArg; if (captureThisArg) { - // `a.b` -> { expression: `(_a = a).b`, thisArg: `_a` } - thisArg = ts.createTempVariable(hoistVariableDeclaration); - expression = ts.createParen(ts.createAssignment(thisArg, expression)); + if (shouldCaptureInTempVariable(expression)) { + thisArg = ts.createTempVariable(hoistVariableDeclaration); + expression = ts.createAssignment(thisArg, expression); + } + else { + thisArg = expression; + } } - expression = ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)); - return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression; - } - function visitNonOptionalElementAccessExpression(node, captureThisArg) { - if (ts.isOptionalChain(node)) { - // If `node` is an optional chain, then it is the outermost chain of an optional expression. - return visitOptionalExpression(node, captureThisArg); - } - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - ts.Debug.assertNotNode(expression, ts.isSyntheticReference); - var thisArg; - if (captureThisArg) { - // `a[b]` -> { expression: `(_a = a)[b]`, thisArg: `_a` } - thisArg = ts.createTempVariable(hoistVariableDeclaration); - expression = ts.createParen(ts.createAssignment(thisArg, expression)); - } - expression = ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); + expression = node.kind === 193 /* PropertyAccessExpression */ + ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) + : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression; } function visitNonOptionalCallExpression(node, captureThisArg) { @@ -77465,8 +77794,8 @@ var ts; function visitNonOptionalExpression(node, captureThisArg) { switch (node.kind) { case 199 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg); - case 193 /* PropertyAccessExpression */: return visitNonOptionalPropertyAccessExpression(node, captureThisArg); - case 194 /* ElementAccessExpression */: return visitNonOptionalElementAccessExpression(node, captureThisArg); + case 193 /* PropertyAccessExpression */: + case 194 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg); case 195 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } @@ -77474,31 +77803,36 @@ var ts; function visitOptionalExpression(node, captureThisArg) { var _a = flattenChain(node), expression = _a.expression, chain = _a.chain; var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0])); - var temp = ts.createTempVariable(hoistVariableDeclaration); var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined; var leftExpression = ts.isSyntheticReference(left) ? left.expression : left; - var rightExpression = temp; + var capturedLeft = leftExpression; + if (shouldCaptureInTempVariable(leftExpression)) { + capturedLeft = ts.createTempVariable(hoistVariableDeclaration); + leftExpression = ts.createAssignment(capturedLeft, leftExpression); + } + var rightExpression = capturedLeft; var thisArg; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { case 193 /* PropertyAccessExpression */: - if (i === chain.length - 1 && captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - rightExpression = ts.createParen(ts.createAssignment(thisArg, rightExpression)); - } - rightExpression = ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)); - break; case 194 /* ElementAccessExpression */: if (i === chain.length - 1 && captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - rightExpression = ts.createParen(ts.createAssignment(thisArg, rightExpression)); + if (shouldCaptureInTempVariable(rightExpression)) { + thisArg = ts.createTempVariable(hoistVariableDeclaration); + rightExpression = ts.createAssignment(thisArg, rightExpression); + } + else { + thisArg = rightExpression; + } } - rightExpression = ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); + rightExpression = segment.kind === 193 /* PropertyAccessExpression */ + ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) + : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; case 195 /* CallExpression */: if (i === 0 && leftThisArg) { - rightExpression = ts.createFunctionCall(rightExpression, leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); + rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 101 /* SuperKeyword */ ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } else { rightExpression = ts.createCall(rightExpression, @@ -77508,22 +77842,27 @@ var ts; } ts.setOriginalNode(rightExpression, segment); } - var target = ts.createConditional(ts.createLogicalOr(ts.createStrictEquality(ts.createAssignment(temp, leftExpression), ts.createNull()), ts.createStrictEquality(temp, ts.createVoidZero())), ts.createVoidZero(), rightExpression); + var target = ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createVoidZero(), rightExpression); return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target; } - function createNotNullCondition(node) { - return ts.createBinary(ts.createBinary(node, ts.createToken(37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(55 /* AmpersandAmpersandToken */), ts.createBinary(node, ts.createToken(37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero())); + function createNotNullCondition(left, right, invert) { + return ts.createBinary(ts.createBinary(left, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(invert ? 56 /* BarBarToken */ : 55 /* AmpersandAmpersandToken */), ts.createBinary(right, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero())); } function transformNullishCoalescingExpression(node) { - var expressions = []; var left = ts.visitNode(node.left, visitor, ts.isExpression); - if (!ts.isIdentifier(left)) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - expressions.push(ts.createAssignment(temp, left)); - left = temp; + var right = left; + if (shouldCaptureInTempVariable(left)) { + right = ts.createTempVariable(hoistVariableDeclaration); + left = ts.createAssignment(right, left); } - expressions.push(ts.createParen(ts.createConditional(createNotNullCondition(left), left, ts.visitNode(node.right, visitor, ts.isExpression)))); - return ts.inlineExpressions(expressions); + return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression)); + } + function shouldCaptureInTempVariable(expression) { + // don't capture identifiers and `this` in a temporary variable + // `super` cannot be captured as it's no real variable + return !ts.isIdentifier(expression) && + expression.kind !== 103 /* ThisKeyword */ && + expression.kind !== 101 /* SuperKeyword */; } } ts.transformESNext = transformESNext; @@ -87681,6 +88020,7 @@ var ts; var combinedStatements; if (ts.isSourceFileJS(currentSourceFile)) { combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); } else { @@ -89452,7 +89792,11 @@ var ts; bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) + return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) + emitSkipped = true; return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -92206,8 +92550,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_20 = types; _d < types_20.length; _d++) { - var directive = types_20[_d]; + for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { + var directive = types_21[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -94082,31 +94426,39 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (system.directoryExists(directoryPath)) { + if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } return false; } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - if (compilerHost.createDirectory) { - compilerHost.createDirectory(directoryPath); - } - else { - system.createDirectory(directoryPath); + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + // NOTE: If patchWriteFileEnsuringDirectory has been called, + // the system.writeFile will do its own directory creation and + // the ensureDirectoriesExist call will always be redundant. + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); } } } var outputFingerprints; - function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + function writeFileWorker(fileName, data, writeByteOrderMark) { + if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) { + system.writeFile(fileName, data, writeByteOrderMark); + return; + } if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = system.createHash(data); // TODO: GH#18217 - var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); + var mtimeBefore = system.getModifiedTime(fileName); if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -94118,32 +94470,13 @@ var ts; } } system.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, mtime: mtimeAfter }); } - function writeFile(fileName, data, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { - writeFileIfUpdated(fileName, data, writeByteOrderMark); - } - else { - system.writeFile(fileName, data, writeByteOrderMark); - } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -95865,9 +96198,16 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - if (fail) - fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + var canonicalFileName_1 = host.getCanonicalFileName(fileName); + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) { + if (fail) { + if (ts.hasJSFileExtension(canonicalFileName_1)) { + fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName); + } + else { + fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + } + } return undefined; } var sourceFile = getSourceFile(fileName); @@ -95881,7 +96221,7 @@ var ts; fail(ts.Diagnostics.File_0_not_found, fileName); } } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) { fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); } } @@ -95939,6 +96279,19 @@ var ts; function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) { if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(fileName); + // If preserveSymlinks is true, module resolution wont jump the symlink + // but the resolved real path may be the .d.ts from project reference + // Note:: Currently we try the real path only if the + // file is from node_modules to avoid having to run real path on all file paths + if (!source && + host.realpath && + options.preserveSymlinks && + ts.isDeclarationFileName(fileName) && + ts.stringContains(fileName, ts.nodeModulesPathPart)) { + var realPath = host.realpath(fileName); + if (realPath !== fileName) + source = getSourceOfProjectReferenceRedirect(realPath); + } if (source) { var file_1 = ts.isString(source) ? findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) : @@ -96469,9 +96822,6 @@ var ts; else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && ts.isIncrementalCompilation(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { @@ -97516,6 +97866,7 @@ var ts; ts.Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = ts.createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -98246,7 +98597,7 @@ var ts; } var state = { fileInfos: fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), @@ -98282,33 +98633,6 @@ var ts; } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; - function convertFromReusableCompilerOptions(options, toAbsolutePath) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - function convertFromReusableCompilerOptionValue(option, value, toAbsolutePath) { - if (option) { - if (option.type === "list") { - var values = value; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value); - } - } - return value; - } function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -99041,7 +99365,7 @@ var ts; function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { return { relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, - ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? + ending: ts.hasJSFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, }; @@ -99127,7 +99451,7 @@ var ts; var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } function numberOfDirectorySeparators(str) { @@ -99261,10 +99585,13 @@ var ts; // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); + var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { return undefined; + } // If the module was found in @types, get the actual Node package name var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); @@ -99489,7 +99816,7 @@ var ts; /** Parses config file using System interface */ function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; @@ -99513,7 +99840,7 @@ var ts; } ts.getErrorSummaryText = getErrorSummaryText; function listFiles(program, writeFileName) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { ts.forEach(program.getSourceFiles(), function (file) { writeFileName(file.fileName); }); @@ -99524,6 +99851,7 @@ var ts; * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -99532,13 +99860,17 @@ var ts; // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + if (!isListFilesOnly) { + ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + } } } // Emit and report any errors we ran into. - var emitResult = program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + var emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: ts.emptyArray } + : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics; ts.addRange(diagnostics, emitDiagnostics); ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); @@ -99641,19 +99973,13 @@ var ts; createHash: ts.maybeBind(host, host.createHash), readDirectory: ts.maybeBind(host, host.readDirectory), }; - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - if (host.createDirectory) - host.createDirectory(directoryPath); - } - } function writeFile(fileName, text, writeByteOrderMark, onError) { try { ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); + // NOTE: If patchWriteFileEnsuringDirectory has been called, + // the host.writeFile will do its own directory creation and + // the ensureDirectoriesExist call will always be redundant. + ts.writeFileEnsuringDirectories(fileName, text, writeByteOrderMark, function (path, data, writeByteOrderMark) { return host.writeFile(path, data, writeByteOrderMark); }, function (path) { return host.createDirectory(path); }, function (path) { return host.directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -101430,30 +101756,25 @@ var ts; setupInitialBuild(state, cancellationToken); var reportQueue = true; var successfulProjects = 0; - var errorProjects = 0; while (true) { var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; - } } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ts.ExitStatus.DiagnosticsPresent_OutputsGenerated : - ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : - ts.ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); }) + ? ts.ExitStatus.Success + : successfulProjects + ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated + : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); @@ -101461,7 +101782,7 @@ var ts; return ts.ExitStatus.InvalidProject_OutputsSkipped; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped; } var options = state.options, host = state.host; var filesToDelete = options.dry ? [] : undefined; @@ -103393,6 +103714,25 @@ var ts; return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); } ts.documentSpansEqual = documentSpansEqual; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + ts.forEachUnique = forEachUnique; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -104140,10 +104480,11 @@ var ts; } var dependencyKeys = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]; var stringContent = host.readFile(fileName); - var content = stringContent && tryParseJson(stringContent); - if (!content) { + if (!stringContent) return undefined; - } + var content = tryParseJson(stringContent); + if (!content) + return false; var info = {}; for (var _i = 0, dependencyKeys_1 = dependencyKeys; _i < dependencyKeys_1.length; _i++) { var key = dependencyKeys_1[_i]; @@ -104668,8 +105009,10 @@ var ts; }); return { spans: spans, endOfLineState: 0 /* None */ }; function pushClassification(start, end, type) { + var length = end - start; + ts.Debug.assert(length > 0, "Classification had non-positive length of " + length); spans.push(start); - spans.push(end - start); + spans.push(length); spans.push(type); } } @@ -105088,8 +105431,7 @@ var ts; return 25 /* bigintLiteral */; } else if (tokenKind === 10 /* StringLiteral */) { - // TODO: GH#18217 - return token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token && token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -105347,7 +105689,7 @@ var ts; var candidates = []; checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); var types = ts.flatMap(candidates, function (candidate) { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); @@ -106497,6 +106839,7 @@ var ts; var completionKind = 5 /* None */; var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; + // This also gets mutated in nested-functions after the return var symbols = []; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; @@ -106603,8 +106946,15 @@ var ts; var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -106621,8 +106971,15 @@ var ts; var type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -106924,7 +107281,7 @@ var ts; typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); } /** - * Gathers symbols that can be imported from other files, deduplicating along the way. Symbols can be “duplicates” + * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, * if and only if the the first can be imported (it may be excluded due to package.json filtering in @@ -107000,7 +107357,7 @@ var ts; // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -107114,7 +107471,16 @@ var ts; } if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) { if (contextToken.parent.kind === 266 /* JsxOpeningElement */) { - return true; + // Two possibilities: + // 1.
/**/ + // - contextToken: GreaterThanToken (before cursor) + // - location: JSXElement + // - different parents (JSXOpeningElement, JSXElement) + // 2. /**/> + // - contextToken: GreaterThanToken (before cursor) + // - location: GreaterThanToken (after cursor) + // - same parent (JSXOpeningElement) + return location.parent.kind !== 266 /* JsxOpeningElement */; } if (contextToken.parent.kind === 267 /* JsxClosingElement */ || contextToken.parent.kind === 265 /* JsxSelfClosingElement */) { return !!contextToken.parent.parent && contextToken.parent.parent.kind === 264 /* JsxElement */; @@ -107189,7 +107555,7 @@ var ts; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 192 /* ObjectLiteralExpression */) { - var typeForObject = typeChecker.getContextualType(objectLikeContainer); + var typeForObject = typeChecker.getContextualType(objectLikeContainer, 4 /* Completion */); if (!typeForObject) return 2 /* Fail */; isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); @@ -107766,6 +108132,8 @@ var ts; return isFunctionLikeBodyKeyword(kind) || kind === 129 /* DeclareKeyword */ || kind === 134 /* ModuleKeyword */ + || kind === 144 /* TypeKeyword */ + || kind === 135 /* NamespaceKeyword */ || ts.isTypeKeyword(kind) && kind !== 145 /* UndefinedKeyword */; case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); @@ -109575,7 +109943,7 @@ var ts; return undefined; } function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet) { - var moduleSourceFile = symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; + var moduleSourceFile = (symbol.flags & 1536 /* Module */) && symbol.declarations && ts.find(symbol.declarations, ts.isSourceFile); if (!moduleSourceFile) return undefined; var exportEquals = symbol.exports.get("export=" /* ExportEquals */); @@ -110300,8 +110668,10 @@ var ts; || exportSpecifier.name.originalKeywordKind === 83 /* DefaultKeyword */; var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); - var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); - searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + var exportInfo = FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker); + if (exportInfo) { + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { @@ -111512,7 +111882,7 @@ var ts; // The property length will have two declarations of property length coming // from Array - Array and Array var documentationComment = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var comment = _a[_i].comment; if (comment === undefined) @@ -111541,7 +111911,7 @@ var ts; function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); @@ -111578,24 +111948,6 @@ var ts; return comment === undefined ? s : s + " " + comment; } } - /** - * Iterates through 'array' by index and performs the callback on each element of array until the callback - * returns a truthy value, then returns that value. - * If no such value is found, the callback is applied to each element of array and undefined is returned. - */ - function forEachUnique(array, callback) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array.indexOf(array[i]) === i) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - } - } - return undefined; - } function getJSDocTagNameCompletions() { return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { @@ -112520,7 +112872,8 @@ var ts; } var declName = ts.getNameOfDeclaration(node); if (declName && ts.isPropertyName(declName)) { - return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 + var propertyName = ts.getPropertyNameForPropertyNameNode(declName); + return propertyName && ts.unescapeLeadingUnderscores(propertyName); } switch (node.kind) { case 200 /* FunctionExpression */: @@ -113290,6 +113643,9 @@ var ts; case 265 /* JsxSelfClosingElement */: case 266 /* JsxOpeningElement */: return spanForJSXAttributes(n.attributes); + case 210 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + return spanForTemplateLiteral(n); } function spanForJSXElement(node) { var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); @@ -113308,6 +113664,12 @@ var ts; } return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } + function spanForTemplateLiteral(node) { + if (node.kind === 14 /* NoSubstitutionTemplateLiteral */ && node.text.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); + } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 18 /* OpenBraceToken */; } // If the block has no leading keywords and is inside an array literal or call expression, @@ -115610,7 +115972,7 @@ var ts; // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration - var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + var locationIsSymbolDeclaration = symbol.declarations && ts.find(symbol.declarations, function (declaration) { return declaration === (location.kind === 128 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { @@ -116517,8 +116879,8 @@ var ts; rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */), // in other cases there should be no space between '?' and next token rule("NoSpaceAfterQuestionMark", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceBeforeDot", anyToken, [24 /* DotToken */, 28 /* QuestionDotToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceAfterDot", [24 /* DotToken */, 28 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBetweenImportParenInImportType", 95 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between @@ -118650,7 +119012,10 @@ var ts; if (ts.isCallOrNewExpression(parent)) { if (!parent.arguments) return false; - var currentNode = ts.Debug.assertDefined(ts.find(parent.arguments, function (arg) { return arg.pos === child.pos; })); + var currentNode = ts.find(parent.arguments, function (arg) { return arg.pos === child.pos; }); + // If it's not one of the arguments, don't look past this + if (!currentNode) + return false; var currentIndex = parent.arguments.indexOf(currentNode); if (currentIndex === 0) return false; // Can't look at previous node if first @@ -119069,6 +119434,18 @@ var ts; cb(tracker); return tracker.getChanges(); }; + ChangeTracker.prototype.pushRaw = function (sourceFile, change) { + ts.Debug.assertEqual(sourceFile.fileName, change.fileName); + for (var _i = 0, _a = change.textChanges; _i < _a.length; _i++) { + var c = _a[_i]; + this.changes.push({ + kind: ChangeKind.Text, + sourceFile: sourceFile, + text: c.newText, + range: ts.createTextRangeFromSpan(c.span), + }); + } + }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); }; @@ -119197,7 +119574,7 @@ var ts; endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); if (!endNode) { if (!ts.isArrowFunction(node)) - return; // Function missing parentheses, give up + return false; // Function missing parentheses, give up // If no `)`, is an arrow function `x => x`, so use the end of the first parameter endNode = ts.first(node.parameters); } @@ -119206,6 +119583,7 @@ var ts; endNode = node.kind !== 241 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + return true; }; ChangeTracker.prototype.tryInsertThisTypeAnnotation = function (sourceFile, node, type) { var start = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1; @@ -120832,20 +121210,20 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, formatContext, preferences); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, formatContext, preferences); }); }, }); @@ -120885,7 +121263,7 @@ var ts; } return errorCode; } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, formatContext, preferences) { if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 103 /* ThisKeyword */) { return undefined; } @@ -120896,7 +121274,7 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken, formatContext, preferences); return parent; } if (ts.isPropertyAccessExpression(parent)) { @@ -120913,7 +121291,7 @@ var ts; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken, formatContext, preferences); return symbol.valueDeclaration; } return undefined; @@ -120927,14 +121305,14 @@ var ts; // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken, formatContext, preferences); return param; } return undefined; @@ -120942,14 +121320,14 @@ var ts; case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host, formatContext, preferences); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } return undefined; @@ -120964,12 +121342,12 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken, formatContext, preferences) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host, formatContext, preferences); } } - function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken, formatContext, preferences) { if (!ts.isIdentifier(parameterDeclaration.name)) { return; } @@ -120985,7 +121363,7 @@ var ts; for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; if (declaration && !declaration.type && !declaration.initializer) { - annotate(changes, sourceFile, declaration, type, program, host); + annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences); } } if (needParens) @@ -121014,7 +121392,7 @@ var ts; ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)), ]); } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken, formatContext, preferences) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); @@ -121025,11 +121403,11 @@ var ts; annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); } else { - annotate(changes, sourceFile, param, type, program, host); + annotate(changes, sourceFile, param, type, program, host, formatContext, preferences); } } } - function annotate(changes, sourceFile, declaration, type, program, host) { + function annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (ts.isInJSFile(sourceFile) && declaration.kind !== 157 /* PropertySignature */) { @@ -121041,11 +121419,32 @@ var ts; var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); addJSDocTags(changes, sourceFile, parent, [typeTag]); } - else { + else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences)) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } } } + function tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences) { + var _a; + if (ts.isLiteralImportTypeNode(typeNode) && typeNode.qualifier && type.symbol) { + // Replace 'import("./a").SomeType' with 'SomeType' and an actual import if possible + var moduleSymbol = (_a = ts.find(type.symbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) === null || _a === void 0 ? void 0 : _a.getSourceFile().symbol; + // Symbol for the left-most thing after the dot + if (moduleSymbol) { + var symbol = ts.getFirstIdentifier(typeNode.qualifier).symbol; + var action = codefix.getImportCompletionAction(symbol, moduleSymbol, sourceFile, symbol.name, host, program, formatContext, declaration.pos, preferences); + if (action.codeAction.changes.length && changes.tryInsertTypeAnnotation(sourceFile, declaration, ts.createTypeReferenceNode(typeNode.qualifier, typeNode.typeArguments))) { + for (var _i = 0, _b = action.codeAction.changes; _i < _b.length; _i++) { + var change = _b[_i]; + var file = sourceFile.fileName === change.fileName ? sourceFile : ts.Debug.assertDefined(program.getSourceFile(change.fileName)); + changes.pushRaw(file, change); + } + return true; + } + } + } + return false; + } function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { var signature = parameterInferences.length && parameterInferences[0].declaration.parent; if (!signature) { @@ -121737,7 +122136,7 @@ var ts; } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); } function addCandidateType(usage, type) { if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { @@ -123544,6 +123943,7 @@ var ts; var filteredCount = 0; var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host); var allSourceFiles = program.getSourceFiles(); + var globalTypingsCache = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); forEachExternalModule(program.getTypeChecker(), allSourceFiles, function (module, sourceFile) { if (sourceFile === undefined) { if (!packageJson || packageJson.allowsImportingAmbientModule(module, allSourceFiles)) { @@ -123553,7 +123953,9 @@ var ts; filteredCount++; } } - else if (sourceFile && sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + else if (sourceFile && + sourceFile !== from && + isImportablePath(from.fileName, sourceFile.fileName, ts.hostGetCanonicalFileName(host), globalTypingsCache)) { if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile, allSourceFiles)) { cb(module); } @@ -123583,10 +123985,13 @@ var ts; * Don't include something from a `node_modules` that isn't actually reachable by a global import. * A relative import to node_modules is usually a bad idea. */ - function isImportablePath(fromPath, toPath) { + function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } function moduleSymbolToValidIdentifier(moduleSymbol, target) { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); @@ -123631,6 +124036,7 @@ var ts; readFile: ts.maybeBind(host, host.readFile), useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || program.getProbableSymlinks, + getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), }; var usesNodeCoreModules; return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; @@ -125206,14 +125612,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); - if (sig.hasRestParameter) { + if (ts.signatureHasRestParameter(sig)) { someSigHasRestParameter = true; } - if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!ts.signatureHasRestParameter(sig) || ts.signatureHasRestParameter(maxArgsSignature))) { maxArgsSignature = sig; } } - var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + var maxNonRestArgs = maxArgsSignature.parameters.length - (ts.signatureHasRestParameter(maxArgsSignature) ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { @@ -127698,7 +128104,7 @@ var ts; if (!selection || !ts.isTypeNode(selection)) return undefined; var checker = context.program.getTypeChecker(); - var firstStatement = ts.Debug.assertDefined(isJS ? ts.findAncestor(selection, isStatementAndHasJSDoc) : ts.findAncestor(selection, ts.isStatement), "Should find a statement"); + var firstStatement = ts.Debug.assertDefined(ts.findAncestor(selection, ts.isStatement), "Should find a statement"); var typeParameters = collectTypeParameters(checker, selection, firstStatement, file); if (!typeParameters) return undefined; @@ -127729,9 +128135,6 @@ var ts; } return undefined; } - function isStatementAndHasJSDoc(n) { - return ts.isStatement(n) && ts.hasJSDocNodes(n); - } function rangeContainsSkipTrivia(r1, node, file) { return ts.rangeContainsStartEnd(r1, ts.skipTrivia(file.text, node.pos), node.end); } @@ -129655,8 +130058,9 @@ var ts; return TypeObject; }()); var SignatureObject = /** @class */ (function () { - function SignatureObject(checker) { + function SignatureObject(checker, flags) { this.checker = checker; + this.flags = flags; } SignatureObject.prototype.getDeclaration = function () { return this.declaration; @@ -129694,13 +130098,12 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + ts.forEachUnique(declarations, function (declaration) { var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); - } + }); } return doc; } @@ -130011,9 +130414,7 @@ var ts; names.push(entry); } else { - if (entry.scriptKind !== 6 /* JSON */) { - names.push(entry.hostFileName); - } + names.push(entry.hostFileName); } }); return names; @@ -130581,12 +130982,11 @@ var ts; var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName, emitOnlyDtsFiles) { - if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + return ts.getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit); } // Signature help /** @@ -133735,16 +134135,31 @@ var ts; case 1: return this.containingProjects[0]; default: - // if this file belongs to multiple projects, the first configured project should be - // the default project; if no configured projects, the first external project should - // be the default project; otherwise the first inferred project should be the default. + // If this file belongs to multiple projects, below is the order in which default project is used + // - for open script info, its default configured project during opening is default if info is part of it + // - first configured project of which script info is not a source of project reference redirect + // - first configured project + // - first external project + // - first inferred project var firstExternalProject = void 0; var firstConfiguredProject = void 0; - for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { - var project = _a[_i]; + var firstNonSourceOfProjectReferenceRedirect = void 0; + var defaultConfiguredProject = void 0; + for (var index = 0; index < this.containingProjects.length; index++) { + var project = this.containingProjects[index]; if (project.projectKind === server.ProjectKind.Configured) { - if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) - return project; + if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) { + // If we havent found default configuredProject and + // its not the last one, find it and use that one if there + if (defaultConfiguredProject === undefined && + index !== this.containingProjects.length - 1) { + defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false; + } + if (defaultConfiguredProject === project) + return project; + if (!firstNonSourceOfProjectReferenceRedirect) + firstNonSourceOfProjectReferenceRedirect = project; + } if (!firstConfiguredProject) firstConfiguredProject = project; } @@ -133752,7 +134167,11 @@ var ts; firstExternalProject = project; } } - return firstConfiguredProject || firstExternalProject || this.containingProjects[0]; + return defaultConfiguredProject || + firstNonSourceOfProjectReferenceRedirect || + firstConfiguredProject || + firstExternalProject || + this.containingProjects[0]; } }; ScriptInfo.prototype.registerFileUpdate = function () { @@ -134051,7 +134470,7 @@ var ts; var Project = /** @class */ (function () { /*@internal*/ function Project( - /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { + /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory, customRealpath) { var _this = this; this.projectName = projectName; this.projectKind = projectKind; @@ -134121,7 +134540,7 @@ var ts; this.trace = function (s) { return host.trace(s); }; } if (host.realpath) { - this.realpath = function (path) { return host.realpath(path); }; + this.realpath = customRealpath || (function (path) { return host.realpath(path); }); } // Use the current directory as resolution root only if the project created using current directory string this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, /*logChangesWhenResolvingModule*/ true); @@ -134162,6 +134581,10 @@ var ts; Project.prototype.installPackage = function (options) { return this.typingsCache.installPackage(__assign(__assign({}, options), { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); }; + /*@internal*/ + Project.prototype.getGlobalTypingsCacheLocation = function () { + return this.getGlobalCache(); + }; Object.defineProperty(Project.prototype, "typingsCache", { get: function () { return this.projectService.typingsCache; @@ -135061,9 +135484,11 @@ var ts; this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } - // Search our peer node_modules, then any globally-specified probe paths - // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ - var searchPaths = __spreadArrays([ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")], this.projectService.pluginProbeLocations); + // Search any globally-specified probe paths, then our peer node_modules + var searchPaths = __spreadArrays(this.projectService.pluginProbeLocations, [ + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ + ts.combinePaths(this.projectService.getExecutingFilePath(), "../../.."), + ]); if (this.projectService.globalPlugins) { var _loop_2 = function (globalPluginName) { // Skip empty names from odd commandline parses @@ -135169,7 +135594,9 @@ var ts; case -1 /* True */: var packageJsonFileName = ts.combinePaths(directory, "package.json"); watchPackageJsonFile(packageJsonFileName); - result.push(ts.Debug.assertDefined(packageJsonCache.getInDirectory(directory))); + var info = packageJsonCache.getInDirectory(directory); + if (info) + result.push(info); } if (rootPath && rootPath === toPath(directory)) { return true; @@ -135337,7 +135764,7 @@ var ts; /*hasExplicitListOfFiles*/ false, /*lastFileExceededProgramSize*/ undefined, /*compilerOptions*/ {}, - /*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; + /*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName), projectService.host.realpath && (function (s) { return _this.getRealpath(s); })) || this; /*@internal*/ _this.canConfigFileJsonReportNoInputFiles = false; /** Ref count to the project when opened from external project */ @@ -135355,19 +135782,31 @@ var ts; ConfiguredProject.prototype.setResolvedProjectReferenceCallbacks = function (projectReferenceCallbacks) { this.projectReferenceCallbacks = projectReferenceCallbacks; }; + ConfiguredProject.prototype.fileExistsIfProjectReferenceDts = function (file) { + var source = this.projectReferenceCallbacks.getSourceOfProjectReferenceRedirect(file); + return source !== undefined ? + ts.isString(source) ? _super.prototype.fileExists.call(this, source) : true : + undefined; + }; /** * This implementation of fileExists checks if the file being requested is * .d.ts file for the referenced Project. * If it is it returns true irrespective of whether that file exists on host */ ConfiguredProject.prototype.fileExists = function (file) { + if (_super.prototype.fileExists.call(this, file)) + return true; + if (!this.useSourceOfProjectReferenceRedirect() || !this.projectReferenceCallbacks) + return false; + if (!ts.isDeclarationFileName(file)) + return false; // Project references go to source file instead of .d.ts file - if (this.useSourceOfProjectReferenceRedirect() && this.projectReferenceCallbacks) { - var source = this.projectReferenceCallbacks.getSourceOfProjectReferenceRedirect(file); - if (source) - return ts.isString(source) ? _super.prototype.fileExists.call(this, source) : true; - } - return _super.prototype.fileExists.call(this, file); + return this.fileOrDirectoryExistsUsingSource(file, /*isFile*/ true); + }; + ConfiguredProject.prototype.directoryExistsIfProjectReferenceDeclDir = function (dir) { + var dirPath = this.toPath(dir); + var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator; + return ts.forEachKey(this.mapOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath || ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator); }); }; /** * This implementation of directoryExists checks if the directory being requested is @@ -135376,8 +135815,10 @@ var ts; */ ConfiguredProject.prototype.directoryExists = function (path) { var _this = this; - if (_super.prototype.directoryExists.call(this, path)) + if (_super.prototype.directoryExists.call(this, path)) { + this.handleDirectoryCouldBeSymlink(path); return true; + } if (!this.useSourceOfProjectReferenceRedirect() || !this.projectReferenceCallbacks) return false; if (!this.mapOfDeclarationDirectories) { @@ -135385,7 +135826,7 @@ var ts; this.projectReferenceCallbacks.forEachResolvedProjectReference(function (ref) { if (!ref) return; - var out = ref.commandLine.options.outFile || ref.commandLine.options.outDir; + var out = ref.commandLine.options.outFile || ref.commandLine.options.out; if (out) { _this.mapOfDeclarationDirectories.set(ts.getDirectoryPath(_this.toPath(out)), true); } @@ -135398,9 +135839,70 @@ var ts; } }); } - var dirPath = this.toPath(path); - var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator; - return !!ts.forEachKey(this.mapOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath || ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator); }); + return this.fileOrDirectoryExistsUsingSource(path, /*isFile*/ false); + }; + ConfiguredProject.prototype.realpathIfSymlinkedProjectReferenceDts = function (s) { + return this.symlinkedFiles && this.symlinkedFiles.get(this.toPath(s)); + }; + ConfiguredProject.prototype.getRealpath = function (s) { + return this.realpathIfSymlinkedProjectReferenceDts(s) || + this.projectService.host.realpath(s); + }; + ConfiguredProject.prototype.handleDirectoryCouldBeSymlink = function (directory) { + if (!this.useSourceOfProjectReferenceRedirect() || !this.projectReferenceCallbacks) + return; + // Because we already watch node_modules, handle symlinks in there + if (!this.realpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) + return; + if (!this.symlinkedDirectories) + this.symlinkedDirectories = ts.createMap(); + var directoryPath = ts.ensureTrailingDirectorySeparator(this.toPath(directory)); + if (this.symlinkedDirectories.has(directoryPath)) + return; + var real = this.projectService.host.realpath(directory); + var realPath; + if (real === directory || + (realPath = ts.ensureTrailingDirectorySeparator(this.toPath(real))) === directoryPath) { + // not symlinked + this.symlinkedDirectories.set(directoryPath, false); + return; + } + this.symlinkedDirectories.set(directoryPath, { + real: ts.ensureTrailingDirectorySeparator(real), + realPath: realPath + }); + }; + ConfiguredProject.prototype.fileOrDirectoryExistsUsingSource = function (fileOrDirectory, isFile) { + var _this = this; + var fileOrDirectoryExistsUsingSource = isFile ? + function (file) { return _this.fileExistsIfProjectReferenceDts(file); } : + function (dir) { return _this.directoryExistsIfProjectReferenceDeclDir(dir); }; + // Check current directory or file + var result = fileOrDirectoryExistsUsingSource(fileOrDirectory); + if (result !== undefined) + return result; + if (!this.symlinkedDirectories) + return false; + var fileOrDirectoryPath = this.toPath(fileOrDirectory); + if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart)) + return false; + if (isFile && this.symlinkedFiles && this.symlinkedFiles.has(fileOrDirectoryPath)) + return true; + // If it contains node_modules check if its one of the symlinked path we know of + return ts.firstDefinedIterator(this.symlinkedDirectories.entries(), function (_a) { + var directoryPath = _a[0], symlinkedDirectory = _a[1]; + if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath)) + return undefined; + var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath)); + if (isFile && result) { + if (!_this.symlinkedFiles) + _this.symlinkedFiles = ts.createMap(); + // Store the real path for the file' + var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, _this.currentDirectory); + _this.symlinkedFiles.set(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), "")); + } + return result; + }) || false; }; /** * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph @@ -135412,6 +135914,8 @@ var ts; this.pendingReload = ts.ConfigFileProgramReloadLevel.None; this.projectReferenceCallbacks = undefined; this.mapOfDeclarationDirectories = undefined; + this.symlinkedDirectories = undefined; + this.symlinkedFiles = undefined; var result; switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: @@ -135522,6 +136026,8 @@ var ts; this.configFileSpecs = undefined; this.projectReferenceCallbacks = undefined; this.mapOfDeclarationDirectories = undefined; + this.symlinkedDirectories = undefined; + this.symlinkedFiles = undefined; _super.prototype.close.call(this); }; /* @internal */ @@ -136378,7 +136884,7 @@ var ts; ts.Debug.assert(info.isOrphan()); var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || this.getOrCreateSingleInferredProjectIfEnabled() || - this.getOrCreateSingleInferredWithoutProjectRoot(info.isDynamic ? this.currentDirectory : ts.getDirectoryPath(info.path)); + this.getOrCreateSingleInferredWithoutProjectRoot(info.isDynamic ? projectRootPath || this.currentDirectory : ts.getDirectoryPath(info.path)); project.addRoot(info); if (info.containingProjects[0] !== project) { // Ensure this is first project, we could be in this scenario because info could be part of orphan project @@ -136701,6 +137207,9 @@ var ts; } ts.Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path)); var projectRootPath = this.openFiles.get(info.path); + var scriptInfo = ts.Debug.assertDefined(this.getScriptInfo(info.path)); + if (scriptInfo.isDynamic) + return undefined; var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName)); var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); }; // If projectRootPath doesn't contain info.path, then do normal search for config file @@ -136725,6 +137234,14 @@ var ts; } while (anySearchPathOk || isSearchPathInProjectRoot()); return undefined; }; + /*@internal*/ + ProjectService.prototype.findDefaultConfiguredProject = function (info) { + if (!info.isScriptOpen()) + return undefined; + var configFileName = this.getConfigFileNameForFile(info); + return configFileName && + this.findConfiguredProjectByProjectName(configFileName); + }; /** * This function tries to search for a tsconfig.json for the given file. * This is different from the method the compiler uses because @@ -137064,7 +137581,9 @@ var ts; }); }; ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) { - if (info.isDynamic || !this.useInferredProjectPerProjectRoot) { + if (!this.useInferredProjectPerProjectRoot || + // Its a dynamic info opened without project root + (info.isDynamic && projectRootPath === undefined)) { return undefined; } if (projectRootPath) { @@ -137323,7 +137842,7 @@ var ts; var isDynamic = server.isDynamicFileName(fileName); ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info or in context of host currentDirectory"; }); ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; }); - ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; }); + ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory || this.useInferredProjectPerProjectRoot, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always be opened with service's current directory or service should support inferred project per projectRootPath."; }); // If the file is not opened by client and the file doesnot exist on the disk, return if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { return; @@ -137334,7 +137853,7 @@ var ts; if (!openedByClient) { this.watchClosedScriptInfo(info); } - else if (!ts.isRootedDiskPath(fileName) && !isDynamic) { + else if (!ts.isRootedDiskPath(fileName) && (!isDynamic || this.currentDirectory !== currentDirectory)) { // File that is opened by user but isn't rooted disk path this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); } @@ -138325,7 +138844,7 @@ var ts; directoriesWithoutPackageJson.set(ts.getDirectoryPath(fileName), true); }, getInDirectory: function (directory) { - return packageJsons.get(ts.combinePaths(directory, "package.json")); + return packageJsons.get(ts.combinePaths(directory, "package.json")) || undefined; }, directoryHasPackageJson: directoryHasPackageJson, searchDirectoryAndAncestors: function (directory) { @@ -138345,7 +138864,7 @@ var ts; }; function addOrUpdate(fileName) { var packageJsonInfo = ts.createPackageJsonInfo(fileName, project); - if (packageJsonInfo) { + if (packageJsonInfo !== undefined) { packageJsons.set(fileName, packageJsonInfo); directoriesWithoutPackageJson.delete(ts.getDirectoryPath(fileName)); } diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index f8215306f30..94c856cfd04 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.7"; + const versionMajorMinor = "3.8"; /** The version of the TypeScript compiler release */ const version: string; } @@ -1964,6 +1964,8 @@ declare namespace ts { DiagnosticsPresent_OutputsSkipped = 1, DiagnosticsPresent_OutputsGenerated = 2, InvalidProject_OutputsSkipped = 3, + ProjectReferenceCycle_OutputsSkipped = 4, + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ProjectReferenceCycle_OutputsSkupped = 4 } export interface EmitResult { @@ -2376,6 +2378,7 @@ declare namespace ts { JSLiteral = 16384, FreshLiteral = 32768, ArrayLiteral = 65536, + ObjectRestType = 131072, ClassOrInterface = 3, } export interface ObjectType extends Type { @@ -3169,8 +3172,9 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + readonly importModuleSpecifierPreference?: "auto" | "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: boolean; @@ -3522,6 +3526,7 @@ declare namespace ts { function isCallExpression(node: Node): node is CallExpression; function isCallChain(node: Node): node is CallChain; function isOptionalChain(node: Node): node is PropertyAccessChain | ElementAccessChain | CallChain; + function isNullishCoalesce(node: Node): boolean; function isNewExpression(node: Node): node is NewExpression; function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression; function isTypeAssertion(node: Node): node is TypeAssertion; @@ -5071,7 +5076,7 @@ declare namespace ts { 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[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; dispose(): void; } @@ -5194,7 +5199,7 @@ declare namespace ts { } interface FileTextChanges { fileName: string; - textChanges: TextChange[]; + textChanges: readonly TextChange[]; isNewFile?: boolean; } interface CodeAction { @@ -6626,9 +6631,11 @@ declare namespace ts.server.protocol { interface DefinitionResponse extends Response { body?: FileSpanWithContext[]; } - interface DefinitionInfoAndBoundSpanReponse extends Response { + interface DefinitionInfoAndBoundSpanResponse extends Response { body?: DefinitionInfoAndBoundSpan; } + /** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */ + type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse; /** * Definition response message. Gives text range for definition. */ @@ -8291,7 +8298,13 @@ declare namespace ts.server.protocol { * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. */ readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** + * Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled, + * member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined + * values, with insertion text to replace preceding `.` tokens with `?.`. + */ + readonly includeAutomaticOptionalChainCompletions?: boolean; + readonly importModuleSpecifierPreference?: "auto" | "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; readonly lazyConfiguredProjectsFromExternalProject?: boolean; readonly providePrefixAndSuffixTextForRename?: boolean; @@ -8556,7 +8569,7 @@ declare namespace ts.server { static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void, logErrors?: (message: string) => void): {} | undefined; isKnownTypesPackageName(name: string): boolean; installPackage(options: InstallPackageOptions): Promise; - private readonly typingsCache; + private get typingsCache(); getCompilationSettings(): CompilerOptions; getCompilerOptions(): CompilerOptions; getNewLine(): string; @@ -8672,23 +8685,31 @@ declare namespace ts.server { readonly canonicalConfigFilePath: NormalizedPath; private projectReferenceCallbacks; private mapOfDeclarationDirectories; + private symlinkedDirectories; + private symlinkedFiles; /** Ref count to the project when opened from external project */ private externalProjectRefCount; private projectErrors; private projectReferences; protected isInitialLoadPending: () => boolean; + private fileExistsIfProjectReferenceDts; /** * This implementation of fileExists checks if the file being requested is * .d.ts file for the referenced Project. * If it is it returns true irrespective of whether that file exists on host */ fileExists(file: string): boolean; + private directoryExistsIfProjectReferenceDeclDir; /** * This implementation of directoryExists checks if the directory being requested is * directory of .d.ts file for the referenced Project. * If it is it returns true irrespective of whether that directory exists on host */ directoryExists(path: string): boolean; + private realpathIfSymlinkedProjectReferenceDts; + private getRealpath; + private handleDirectoryCouldBeSymlink; + private fileOrDirectoryExistsUsingSource; /** * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph * @returns: true if set of files in the project stays the same and false - otherwise. diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index cb0c22f9ca6..df037f4846b 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -87,67 +87,20 @@ var __rest = (this && this.__rest) || function (s, e) { } return t; }; +/* @internal */ var ts; (function (ts) { - // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. - // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.7"; - /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; -})(ts || (ts = {})); -(function (ts) { - /* @internal */ - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - ts.emptyArray = []; - /** Create a MapLike with good performance. */ - function createDictionaryObject() { - var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - return map; - } - /** Create a new map. If a template object is provided, the map will copy entries from it. */ - function createMap() { - return new ts.MapCtr(); - } - ts.createMap = createMap; - function createMapFromEntries(entries) { - var map = createMap(); - for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { - var _a = entries_1[_i], key = _a[0], value = _a[1]; - map.set(key, value); + function createMapShim() { + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; } - return map; - } - ts.createMapFromEntries = createMapFromEntries; - function createMapFromTemplate(template) { - var map = new ts.MapCtr(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in template) { - if (hasOwnProperty.call(template, key)) { - map.set(key, template[key]); - } - } - return map; - } - ts.createMapFromTemplate = createMapFromTemplate; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // eslint-disable-next-line no-in-operator - ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - // Keep the class inside a function so it doesn't get compiled if it's not used. - function shimMap() { var MapIterator = /** @class */ (function () { function MapIterator(currentEntry, selector) { this.currentEntry = currentEntry; @@ -283,7 +236,75 @@ var ts; return class_1; }()); } - ts.shimMap = shimMap; + ts.createMapShim = createMapShim; +})(ts || (ts = {})); +var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.8"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".0-dev"; +})(ts || (ts = {})); +(function (ts) { + /* @internal */ + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + /** + * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). + */ + function tryGetNativeMap() { + // Internet Explorer's Map doesn't support iteration, so don't use it. + // eslint-disable-next-line no-in-operator + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; + } + ts.tryGetNativeMap = tryGetNativeMap; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + ts.Map = ts.tryGetNativeMap() || (function () { + // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it. + if (typeof ts.createMapShim === "function") { + return ts.createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); + /** Create a new map. */ + function createMap() { + return new ts.Map(); + } + ts.createMap = createMap; + /** Create a new map from an array of entries. */ + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + /** Create a new map from a template object is provided, the map will copy entries from it. */ + function createMapFromTemplate(template) { + var map = new ts.Map(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; function length(array) { return array ? array.length : 0; } @@ -1865,20 +1886,6 @@ var ts; return str.indexOf(substring) !== -1; } ts.stringContains = stringContains; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -2192,11 +2199,14 @@ var ts; if (isFlags) { var result = ""; var remainingFlags = value; - for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { - var _a = members[i], enumValue = _a[0], enumName = _a[1]; - if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; + if (enumValue > value) { + break; + } + if (enumValue !== 0 && enumValue & value) { + result = "" + result + (result ? "|" : "") + enumName; remainingFlags &= ~enumValue; - result = "" + enumName + (result ? "|" : "") + result; } } if (remainingFlags === 0) { @@ -2204,8 +2214,8 @@ var ts; } } else { - for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { - var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + for (var _b = 0, members_2 = members; _b < members_2.length; _b++) { + var _c = members_2[_b], enumValue = _c[0], enumName = _c[1]; if (enumValue === value) { return enumName; } @@ -2279,6 +2289,33 @@ var ts; ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; var isDebugInfoEnabled = false; + var extendedDebugModule; + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + Debug.formatControlFlowGraph = formatControlFlowGraph; + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator + Object.defineProperties(flowNode, { + __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } }, + __debugToString: { value: function () { return formatControlFlowGraph(this); } } + }); + } + } + } + Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; /** * Injects debug information into frequently used types. */ @@ -2322,6 +2359,20 @@ var ts; }); } } + // attempt to load extended debugging information + try { + if (ts.sys && ts.sys.require) { + var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath())); + var result = ts.sys.require(basePath, "./compiler-debug"); + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch (_a) { + // do nothing + } isDebugInfoEnabled = true; } Debug.enableDebugInfo = enableDebugInfo; @@ -2485,8 +2536,6 @@ var ts; } /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - var args = typeof process === "undefined" ? [] : process.argv; - ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(args)); })(ts || (ts = {})); /* @internal */ var ts; @@ -3381,6 +3430,7 @@ var ts; /* @internal */ TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + // NOTE: Ensure this is up-to-date with src/debug/debug.ts var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -3436,6 +3486,8 @@ var ts; // When build skipped because passed in project is invalid ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped"; // When build is skipped because project references form cycle + ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ @@ -3445,6 +3497,14 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + /* @internal */ + var ContextFlags; + (function (ContextFlags) { + ContextFlags[ContextFlags["None"] = 0] = "None"; + ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; + ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; + ContextFlags[ContextFlags["Completion"] = 4] = "Completion"; + })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {})); // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { @@ -3847,19 +3907,20 @@ var ts; ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 131072] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 262144] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 524288] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 1048576] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 786432] = "RequiresWidening"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 1835008] = "PropagatingFlags"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -3886,6 +3947,20 @@ var ts; SignatureKind[SignatureKind["Call"] = 0] = "Call"; SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + /* @internal */ + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter"; + SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes"; + SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain"; + SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain"; + // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us + // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when + // instantiating the return type. + SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags"; + SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags"; + })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {})); var IndexKind; (function (IndexKind) { IndexKind[IndexKind["String"] = 0] = "String"; @@ -4886,16 +4961,6 @@ var ts; } } ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; - function recursiveCreateDirectory(directoryPath, sys) { - var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); - if (shouldCreateParent) { - recursiveCreateDirectory(basePath, sys); - } - if (shouldCreateParent || !sys.directoryExists(directoryPath)) { - sys.createDirectory(directoryPath); - } - } /** * patch writefile to create folder before writing the file */ @@ -4904,11 +4969,7 @@ var ts; // patch writefile to create folder before writing the file var originalWriteFile = sys.writeFile; sys.writeFile = function (path, data, writeBom) { - var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); - if (directoryPath && !sys.directoryExists(directoryPath)) { - recursiveCreateDirectory(directoryPath, sys); - } - originalWriteFile.call(sys, path, data, writeBom); + return ts.writeFileEnsuringDirectories(path, data, !!writeBom, function (path, data, writeByteOrderMark) { return originalWriteFile.call(sys, path, data, writeByteOrderMark); }, function (path) { return sys.createDirectory(path); }, function (path) { return sys.directoryExists(path); }); }; } ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory; @@ -5057,6 +5118,15 @@ var ts; bufferFrom: bufferFrom, base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + require: function (baseDir, moduleName) { + try { + var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath: modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error: error }; + } + } }; return nodeSystem; /** @@ -5195,6 +5265,7 @@ var ts; if (fsSupportsRecursive) { return watchDirectoryUsingFsWatch; } + // defer watchDirectoryRecursively as it depends on `ts.createMap()` which may not be usable yet. var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? createWatchDirectoryUsing(fsWatchFile) : tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? @@ -5639,6 +5710,673 @@ var ts; ts.Debug.isDebugging = true; } })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + //// Path Tests + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + //// Path Parsing + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArrays([root], rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + //// Path Formatting + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + //// Path Normalization + /** + * Normalize path separators, converting `\` into `/`. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + //// Path Comparisons + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * @deprecated Use `containsPath` if possible. + */ + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + //// Relative Paths + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArrays([""], relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; +})(ts || (ts = {})); // // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ @@ -5666,7 +6404,7 @@ var ts; An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), - An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), @@ -5874,7 +6612,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd_1323", "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5910,6 +6648,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"), 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), @@ -6037,7 +6776,6 @@ var ts; Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), @@ -6207,8 +6945,8 @@ var ts; JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2610, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_proper_2610", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member property."), - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2611, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_access_2611", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member accessor."), + _0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property: diag(2610, ts.DiagnosticCategory.Error, "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610", "'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property."), + _0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor: diag(2611, ts.DiagnosticCategory.Error, "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611", "'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor."), Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), @@ -6431,6 +7169,8 @@ var ts; Parameter_0_of_accessor_has_or_is_using_private_name_1: diag(4106, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106", "Parameter '{0}' of accessor has or is using private name '{1}'."), Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2: diag(4107, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107", "Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'."), Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4108, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108", "Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named."), + Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), + Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -6438,6 +7178,7 @@ var ts; Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Unknown_compiler_option_0_Did_you_mean_1: diag(5025, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"), Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), @@ -6468,6 +7209,7 @@ var ts; 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}'?"), 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."), @@ -6514,7 +7256,7 @@ var ts; Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has an unsupported extension. The only supported extensions are {1}."), Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), @@ -6722,6 +7464,8 @@ var ts; 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."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), + File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -6825,6 +7569,7 @@ var ts; Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), + Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"), Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), @@ -9057,7 +9802,7 @@ var ts; ts.getDeclarationOfKind = getDeclarationOfKind; /** Create a new escaped identifier map. */ function createUnderscoreEscapedMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; function hasEntries(map) { @@ -9113,13 +9858,6 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -9926,6 +10664,11 @@ var ts; break; case 201 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); + case 275 /* CaseClause */: + case 276 /* DefaultClause */: + var start = ts.skipTrivia(sourceFile.text, node.pos); + var end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return ts.createTextSpanFromBounds(start, end); } if (errorNode === undefined) { // If we don't have a better node, then just set the error on the first token of @@ -10738,7 +11481,7 @@ var ts; (node.typeArguments[0].kind === 142 /* StringKeyword */ || node.typeArguments[0].kind === 139 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 195 /* CallExpression */) { return false; } @@ -10750,7 +11493,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -10972,27 +11715,31 @@ var ts; isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true); } ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; - function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { - return isLiteralLikeElementAccess(node) - && ((!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */) || - isEntityNameExpression(node.expression) || - isBindableStaticElementAccessExpression(node.expression, /*excludeThisKeyword*/ true)); - } - ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression; + /** x.y OR x[0] */ function isLiteralLikeAccess(node) { return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node); } ts.isLiteralLikeAccess = isLiteralLikeAccess; + /** x[0] OR x['a'] OR x[Symbol.y] */ function isLiteralLikeElementAccess(node) { return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) || isWellKnownSymbolSyntactically(node.argumentExpression)); } ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; + /** Any series of property and element accesses. */ function isBindableStaticAccessExpression(node, excludeThisKeyword) { return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */ || isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; + /** Any series of property and element accesses, ending in a literal element access */ + function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { + return isLiteralLikeElementAccess(node) + && ((!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */) || + isEntityNameExpression(node.expression) || + isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true)); + } + ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression; function isBindableStaticNameExpression(node, excludeThisKeyword) { return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword); } @@ -11021,7 +11768,7 @@ var ts; if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) { return 0 /* None */; } - if (isBindableStaticNameExpression(expr.left.expression) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { // F.prototype = { ... } return 6 /* Prototype */; } @@ -11077,13 +11824,17 @@ var ts; nextToLast = nextToLast.expression; } var id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { - // exports.name = expr OR module.exports.name = expr + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + // ExportsProperty does not support binding with computed names + isBindableStaticAccessExpression(lhs)) { + // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return 1 /* ExportsProperty */; } - // F.G...x = expr - return 5 /* Property */; + if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs) && lhs.expression.kind !== 103 /* ThisKeyword */)) { + // F.G...x = expr + return 5 /* Property */; + } } return 0 /* None */; } @@ -12405,7 +13156,7 @@ var ts; */ function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); var extensionless = ts.removeFileExtension(relativePath); @@ -12488,6 +13239,25 @@ var ts; }, sourceFiles); } ts.writeFile = writeFile; + function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists); + createDirectory(directoryPath); + } + } + function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) { + // PERF: Checking for directory existence is expensive. Instead, assume the directory exists + // and fall back to creating it if the file write fails. + try { + writeFile(path, data, writeByteOrderMark); + } + catch (_a) { + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists); + writeFile(path, data, writeByteOrderMark); + } + } + ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories; function getLineOfLocalPosition(currentSourceFile, pos) { return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; } @@ -12927,6 +13697,23 @@ var ts; return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function getFirstIdentifier(node) { + switch (node.kind) { + case 75 /* Identifier */: + return node; + case 152 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 75 /* Identifier */); + return node; + case 193 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 75 /* Identifier */); + return node; + } + } + ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { return node.kind === 75 /* Identifier */ || node.kind === 103 /* ThisKeyword */ || node.kind === 193 /* PropertyAccessExpression */ && isDottedName(node.expression) || @@ -13445,20 +14232,6 @@ var ts; }); } ts.mutateMap = mutateMap; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); @@ -13485,7 +14258,7 @@ var ts; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { @@ -14550,11 +15323,47 @@ var ts; } ts.isCallChain = isCallChain; function isOptionalChain(node) { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + var kind = node.kind; + return !!(node.flags & 32 /* OptionalChain */) && + (kind === 193 /* PropertyAccessExpression */ + || kind === 194 /* ElementAccessExpression */ + || kind === 195 /* CallExpression */); } ts.isOptionalChain = isOptionalChain; + /* @internal */ + function isOptionalChainRoot(node) { + return isOptionalChain(node) && !!node.questionDotToken; + } + ts.isOptionalChainRoot = isOptionalChainRoot; + /** + * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`). + */ + /* @internal */ + function isExpressionOfOptionalChainRoot(node) { + return isOptionalChainRoot(node.parent) && node.parent.expression === node; + } + ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot; + /** + * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`: + * + * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`) + * 2. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain) + * 3. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is + * the end of the chain starting at `c?.`) + * 4. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is + * the end of the chain starting at `a?.`) + */ + /* @internal */ + function isOutermostOptionalChain(node) { + return !isOptionalChain(node.parent) // cases 1 and 2 + || isOptionalChainRoot(node.parent) // case 3 + || node !== node.parent.expression; // case 4 + } + ts.isOutermostOptionalChain = isOutermostOptionalChain; + function isNullishCoalesce(node) { + return node.kind === 208 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; + } + ts.isNullishCoalesce = isNullishCoalesce; function isNewExpression(node) { return node.kind === 196 /* NewExpression */; } @@ -15825,11 +16634,6 @@ var ts; return node.kind === 162 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; - /* @internal */ - function isOptionalChainRoot(node) { - return ts.isOptionalChain(node) && !!node.questionDotToken; - } - ts.isOptionalChainRoot = isOptionalChainRoot; /** True if has jsdoc nodes attached to it. */ /* @internal */ // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times @@ -15916,7 +16720,12 @@ var ts; this.checker = checker; } } - function Signature() { } + function Signature(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } function Node(kind, pos, end) { this.pos = pos; this.end = end; @@ -16191,273 +17000,6 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - /** - * Normalize path separators. - */ - function normalizeSlashes(path) { - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - function isVolumeCharacter(charCode) { - return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || - (charCode >= 65 /* A */ && charCode <= 90 /* Z */); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; - if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; - } - return -1; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - // POSIX or UNC - if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; // POSIX: "/" (or non-normalized "\") - var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; // UNC: "//server" or "\\server" - return p1 + 1; // UNC: "//server/" or "\\server\" - } - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) - return 2; // DOS: "c:" (but not "c:d") - } - // URL - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - // relative - return 0; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - // TODO(rbuckton): replace references with `resolvePath` - function normalizePath(path) { - return ts.resolvePath(path); - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - // If the path provided is itself the root, then return it. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = ts.removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - /** - * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArrays([root], rest); - } - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = ts.combinePaths(currentDirectory, path); - var rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - ts.getPathComponents = getPathComponents; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - */ - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var result = ts.createMap(); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { @@ -16474,15 +17016,15 @@ var ts; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { aParts.pop(); bParts.pop(); } - return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; } // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. @@ -16492,229 +17034,8 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); - var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArrays([""], relative, components); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - */ - function ensurePathIsNonModuleName(path) { - return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function getBaseFileName(path, extensions, ignoreCase) { - path = ts.normalizeSlashes(path); - // if the path provided is itself the root, then it has not file name. - var rootLength = ts.getRootLength(path); - if (rootLength === path.length) - return ""; - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - /** - * Combines paths. If a path is absolute, it replaces any previous path. - */ - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = ts.normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = ts.normalizeSlashes(relativePath); - if (!path || ts.getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. - */ - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - var combined = ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : ts.normalizeSlashes(path); - var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.resolvePath = resolvePath; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path) { - if (path.length === 0) - return false; - var ch = path.charCodeAt(path.length - 1); - return ch === 47 /* slash */ || ch === 92 /* backslash */; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - // check path for these segments: '', '.'. '..' - var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - var aRoot = a.substring(0, ts.getRootLength(a)); - var bRoot = b.substring(0, ts.getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0 /* EqualTo */) { - return result; - } - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); - var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_1 = componentComparer(aComponents[i], bComponents[i]); - if (result_1 !== 0 /* EqualTo */) { - return result_1; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - /** - * Performs a case-sensitive comparison of two paths. - */ - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); - var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function isDirectorySeparator(charCode) { - return charCode === 47 /* slash */ || charCode === 92 /* backslash */; - } function stripLeadingDirectorySeparator(s) { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); @@ -16733,10 +17054,6 @@ var ts; return "\\" + match; } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -16812,7 +17129,7 @@ var ts; } // getNormalizedPathComponents includes the separator for the root component. // We need to remove to create our regex correctly. - components[0] = removeTrailingDirectorySeparator(components[0]); + components[0] = ts.removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); } @@ -16874,7 +17191,7 @@ var ts; function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); + var absolutePath = ts.combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), @@ -16903,7 +17220,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -16913,8 +17230,8 @@ var ts; visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) @@ -16941,8 +17258,8 @@ var ts; } for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { visitDirectory(name, absoluteName, depth); @@ -16964,14 +17281,14 @@ var ts; var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") - var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include)); // Append the literal and canonical candidate base paths. includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -16988,9 +17305,9 @@ var ts; var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { // No "*" or "?" in the path - return !hasExtension(absolute) + return !ts.hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -17062,10 +17379,6 @@ var ts; return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJSFileExtension = hasJSFileExtension; - function hasJSOrJsonFileExtension(fileName) { - return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); - } - ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; function hasTSFileExtension(fileName) { return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -17155,14 +17468,9 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); @@ -17205,36 +17513,6 @@ var ts; return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") - extensions = [extensions]; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -18442,6 +18720,9 @@ var ts; function doInYieldAndAwaitContext(func) { return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func); } + function doOutsideOfYieldAndAwaitContext(func) { + return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func); + } function inContext(flags) { return (contextFlags & flags) !== 0; } @@ -22713,18 +22994,7 @@ var ts; node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); - // For instance properties specifically, since they are evaluated inside the constructor, - // we do *not * want to parse yield expressions, so we specifically turn the yield context - // off. The grammar would look something like this: - // - // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; - // - // The checker may still error in the static case to explicitly disallow the yield expression. - node.initializer = ts.hasModifier(node, 32 /* Static */) - ? allowInAnd(parseInitializer) - : doOutsideOfContext(8192 /* YieldContext */ | 4096 /* DisallowInContext */, parseInitializer); + node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer); parseSemicolon(); return finishNode(node); } @@ -23015,7 +23285,7 @@ var ts; parseExpected(87 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(18 /* OpenBraceToken */)) { - node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); }); parseExpected(19 /* CloseBraceToken */); } else { @@ -25077,6 +25347,15 @@ var ts; isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, // Basic { name: "target", @@ -25908,8 +26187,7 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { - var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; + function parseCommandLineWorker(getOptionNameMap, diagnostics, commandLine, readFile) { var options = {}; var fileNames = []; var errors = []; @@ -25936,7 +26214,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); + errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -25972,7 +26250,13 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); + var possibleOption = ts.getSpellingSuggestion(s, ts.optionDeclarations, function (opt) { return "--" + opt.name; }); + if (possibleOption) { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownDidYouMeanDiagnostic, s, possibleOption.name)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownOptionDiagnostic, s)); + } } } else { @@ -26015,11 +26299,13 @@ var ts; parseStrings(args); } } + var compilerOptionsDefaultDiagnostics = { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument + }; function parseCommandLine(commandLine, readFile) { - return parseCommandLineWorker(getOptionNameMap, [ - ts.Diagnostics.Unknown_compiler_option_0, - ts.Diagnostics.Compiler_option_0_expects_an_argument - ], commandLine, readFile); + return parseCommandLineWorker(getOptionNameMap, compilerOptionsDefaultDiagnostics, commandLine, readFile); } ts.parseCommandLine = parseCommandLine; /** @internal */ @@ -26044,10 +26330,11 @@ var ts; function parseBuildCommand(args) { var buildOptionNameMap; var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; - var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ - ts.Diagnostics.Unknown_build_option_0, - ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 - ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + }, args), options = _a.options, projects = _a.fileNames, errors = _a.errors; var buildOptions = options; if (projects.length === 0) { // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." @@ -26069,6 +26356,7 @@ var ts; return { buildOptions: buildOptions, projects: projects, errors: errors }; } ts.parseBuildCommand = parseBuildCommand; + /* @internal */ function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -26077,104 +26365,7 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - /* @internal */ - function printVersion() { - ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); - } - ts.printVersion = printVersion; - /* @internal */ - function printHelp(optionsList, syntaxPrefix) { - if (syntaxPrefix === void 0) { syntaxPrefix = ""; } - var output = []; - // We want to align our "syntax" and "examples" commands to a certain margin. - var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); - // Build up the syntactic skeleton. - var syntax = makePadding(marginLength - syntaxLength); - syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; - output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); - output.push(ts.sys.newLine + ts.sys.newLine); - // Build up the list of examples. - var padding = makePadding(marginLength); - output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); - output.push(padding + "tsc @args.txt" + ts.sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); - output.push(ts.sys.newLine); - output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); - // We want our descriptions to align at the same column in our output, - // so we keep track of the longest option usage string. - marginLength = 0; - var usageColumn = []; // Things like "-d, --declaration" go in here. - var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind - for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { - var option = optionsList_1[_i]; - // If an option lacks a description, - // it is not officially supported. - if (!option.description) { - continue; - } - var usageText_1 = " "; - if (option.shortName) { - usageText_1 += "-" + option.shortName; - usageText_1 += getParamType(option); - usageText_1 += ", "; - } - usageText_1 += "--" + option.name; - usageText_1 += getParamType(option); - usageColumn.push(usageText_1); - var description = void 0; - if (option.name === "lib") { - description = getDiagnosticText(option.description); - var element = option.element; - var typeMap = element.type; - optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); - } - else { - description = getDiagnosticText(option.description); - } - descriptionColumn.push(description); - // Set the new margin for the description column if necessary. - marginLength = Math.max(usageText_1.length, marginLength); - } - // Special case that can't fit in the loop. - var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; - var kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { - var kind = kindsList_1[_a]; - output.push(kind + " "); - } - output.push(ts.sys.newLine); - } - } - for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { - var line = output_1[_b]; - ts.sys.write(line); - } - return; - function getParamType(option) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - } - ts.printHelp = printHelp; + ts.getDiagnosticText = getDiagnosticText; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -26258,19 +26449,28 @@ var ts; name: "compilerOptions", type: "object", elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1 + }, }, { name: "typingOptions", type: "object", elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 + }, }, { name: "typeAcquisition", type: "object", elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 + } }, { name: "extends", @@ -26335,7 +26535,7 @@ var ts; function isRootOptionMap(knownOptions) { return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } - function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; @@ -26352,8 +26552,19 @@ var ts; var textOfKey = ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; - if (keyText && extraKeyDiagnosticMessage && !option) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + if (keyText && extraKeyDiagnostics && !option) { + if (knownOptions) { + var possibleOption = ts.getSpellingSuggestion(keyText, ts.arrayFrom(knownOptions.keys()), ts.identity); + if (possibleOption) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownDidYouMeanDiagnostic, keyText, possibleOption)); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } } var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { @@ -26437,8 +26648,8 @@ var ts; // vs what we set in the json // If need arises, we can modify this interface and callbacks as needed if (option) { - var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; - return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName); } else { return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, @@ -26493,7 +26704,7 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign(__assign({ compilerOptions: __assign(__assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; @@ -26514,12 +26725,12 @@ var ts; return undefined; return specs; } - function matchesSpecs(path, includeSpecs, excludeSpecs) { + function matchesSpecs(path, includeSpecs, excludeSpecs, host) { if (!includeSpecs) return function (_) { return true; }; - var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); - var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); - var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; @@ -26696,6 +26907,35 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + /* @internal */ + function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + var result = {}; + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name in options) { + if (ts.hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; + function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option) { + if (option.type === "list") { + var values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value); + } + } + return value; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -27084,7 +27324,7 @@ var ts; } function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); - convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, compilerOptionsDefaultDiagnostics, errors); if (configFileName) { options.configFilePath = ts.normalizeSlashes(configFileName); } @@ -27096,10 +27336,14 @@ var ts; function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); - convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + var diagnostics = { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1, + }; + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, diagnostics, errors); return options; } - function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnostics, errors) { if (!jsonOptions) { return; } @@ -27110,7 +27354,13 @@ var ts; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } else { - errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + var possibleOption = ts.getSpellingSuggestion(id, optionDeclarations, function (opt) { return opt.name; }); + if (possibleOption) { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownDidYouMeanDiagnostic, id, possibleOption.name)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownOptionDiagnostic, id)); + } } } } @@ -27146,7 +27396,7 @@ var ts; } function normalizeNonListOptionValue(option, basePath, value) { if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + value = ts.getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } @@ -28930,7 +29180,10 @@ var ts; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); - var flowNodeCreated = ts.identity; + function initFlowNode(node) { + ts.Debug.attachFlowNodeDebugInfo(node); + return node; + } var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -28959,6 +29212,7 @@ var ts; var currentReturnTarget; var currentTrueTarget; var currentFalseTarget; + var currentExceptionTarget; var preSwitchCaseFlow; var activeLabels; var hasExplicitReturn; @@ -28994,6 +29248,9 @@ var ts; symbolCount = 0; skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); + // Attach debugging information if necessary + ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); + ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -29016,6 +29273,7 @@ var ts; currentReturnTarget = undefined; currentTrueTarget = undefined; currentFalseTarget = undefined; + currentExceptionTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; emitFlags = 0 /* None */; @@ -29337,11 +29595,11 @@ var ts; blockScopeContainer.locals = undefined; } if (containerFlags & 4 /* IsControlFlowContainer */) { - var saveFlowNodeCreated = flowNodeCreated; var saveCurrentFlow = currentFlow; var saveBreakTarget = currentBreakTarget; var saveContinueTarget = currentContinueTarget; var saveReturnTarget = currentReturnTarget; + var saveExceptionTarget = currentExceptionTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && @@ -29349,7 +29607,7 @@ var ts; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isIIFE) { - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.node = node; } @@ -29357,11 +29615,11 @@ var ts; // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. currentReturnTarget = isIIFE || node.kind === 161 /* Constructor */ ? createBranchLabel() : undefined; + currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = ts.identity; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~2816 /* ReachabilityAndEmitFlags */; @@ -29387,9 +29645,9 @@ var ts; currentBreakTarget = saveBreakTarget; currentContinueTarget = saveContinueTarget; currentReturnTarget = saveReturnTarget; + currentExceptionTarget = saveExceptionTarget; activeLabels = saveActiveLabels; hasExplicitReturn = saveHasExplicitReturn; - flowNodeCreated = saveFlowNodeCreated; } else if (containerFlags & 64 /* IsInterface */) { seenThisKeyword = false; @@ -29530,9 +29788,6 @@ var ts; case 309 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; - case 307 /* JSDocClassTag */: - bindJSDocClassTag(node); - break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 288 /* SourceFile */: { bindEachFunctionsFirst(node.statements); @@ -29572,9 +29827,8 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 103 /* ThisKeyword */ || expr.kind === 101 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && - ts.isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + ts.isOptionalChain(expr); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -29631,10 +29885,10 @@ var ts; return isNarrowableReference(expr); } function createBranchLabel() { - return { flags: 4 /* BranchLabel */, antecedents: undefined }; + return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); } function createLoopLabel() { - return { flags: 8 /* LoopLabel */, antecedents: undefined }; + return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined }); } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag @@ -29653,36 +29907,32 @@ var ts; if (!expression) { return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - if (!ts.isOptionalChainRoot(expression.parent)) { - return unreachableFlow; - } + if ((expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) && + !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) { + return unreachableFlow; } if (!isNarrowingExpression(expression)) { return antecedent; } setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: flags, antecedent: antecedent, node: expression }); + return initFlowNode({ flags: flags, antecedent: antecedent, node: expression }); } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { - return antecedent; - } setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd }); + return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd }); } - function createFlowAssignment(antecedent, node) { + function createFlowMutation(flags, antecedent, node) { setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 16 /* Assignment */, antecedent: antecedent, node: node }); + var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node }); + if (currentExceptionTarget) { + addAntecedent(currentExceptionTarget, result); + } + return result; } function createFlowCall(antecedent, node) { setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 512 /* Call */, antecedent: antecedent, node: node }); - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }); + return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node }); } function finishFlowLabel(flow) { var antecedents = flow.antecedents; @@ -29742,7 +29992,7 @@ var ts; } function bindCondition(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); - if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && isOutermostOptionalChain(node))) { + if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -29873,87 +30123,56 @@ var ts; } function bindTryStatement(node) { var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - var tryPriors = []; - var oldFlowNodeCreated = flowNodeCreated; - // We hook the creation of all flow nodes within the `try` scope and store them so we can add _all_ of them - // as possible antecedents of the start of the `catch` or `finally` blocks. - // Don't bother intercepting the call if there's no finally or catch block that needs the information - if (node.catchClause || node.finallyBlock) { - flowNodeCreated = function (node) { return (tryPriors.push(node), node); }; - } + // We conservatively assume that *any* code in the try block can cause an exception, but we only need + // to track code that causes mutations (because only mutations widen the possible control flow type of + // a variable). The currentExceptionTarget is the target label for control flows that result from + // exceptions. We add all mutation flow nodes as antecedents of this label such that we can analyze them + // as possible antecedents of the start of catch or finally blocks. Furthermore, we add the current + // control flow to represent exceptions that occur before any mutations. + var saveExceptionTarget = currentExceptionTarget; + currentExceptionTarget = createBranchLabel(); + addAntecedent(currentExceptionTarget, currentFlow); bind(node.tryBlock); - flowNodeCreated = oldFlowNodeCreated; addAntecedent(preFinallyLabel, currentFlow); var flowAfterTry = currentFlow; var flowAfterCatch = unreachableFlow; if (node.catchClause) { - currentFlow = preTryFlow; - if (tryPriors.length) { - var preCatchFlow = createBranchLabel(); - addAntecedent(preCatchFlow, currentFlow); - for (var _i = 0, tryPriors_1 = tryPriors; _i < tryPriors_1.length; _i++) { - var p = tryPriors_1[_i]; - addAntecedent(preCatchFlow, p); - } - currentFlow = finishFlowLabel(preCatchFlow); - } + // Start of catch clause is the target of exceptions from try block. + currentFlow = finishFlowLabel(currentExceptionTarget); + // The currentExceptionTarget now represents control flows from exceptions in the catch clause. + // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block + // acts like a second try block. + currentExceptionTarget = createBranchLabel(); + addAntecedent(currentExceptionTarget, currentFlow); bind(node.catchClause); addAntecedent(preFinallyLabel, currentFlow); flowAfterCatch = currentFlow; } + var exceptionTarget = finishFlowLabel(currentExceptionTarget); + currentExceptionTarget = saveExceptionTarget; if (node.finallyBlock) { - // We add the nodes within the `try` block to the `finally`'s antecedents if there's no catch block - // (If there is a `catch` block, it will have all these antecedents instead, and the `finally` will - // have the end of the `try` block and the end of the `catch` block) - var preFinallyPrior = preTryFlow; - if (!node.catchClause) { - if (tryPriors.length) { - var preFinallyFlow_1 = createBranchLabel(); - addAntecedent(preFinallyFlow_1, preTryFlow); - for (var _a = 0, tryPriors_2 = tryPriors; _a < tryPriors_2.length; _a++) { - var p = tryPriors_2[_a]; - addAntecedent(preFinallyFlow_1, p); - } - preFinallyPrior = finishFlowLabel(preFinallyFlow_1); - } - } - // in finally flow is combined from pre-try/flow from try/flow from catch - // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable - // also for finally blocks we inject two extra edges into the flow graph. - // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it - // second -> edge that represents post-finally flow. - // these edges are used in following scenario: - // let a; (1) - // try { a = someOperation(); (2)} - // finally { (3) console.log(a) } (4) - // (5) a - // flow graph for this case looks roughly like this (arrows show ): - // (1-pre-try-flow) <--.. <-- (2-post-try-flow) - // ^ ^ - // |*****(3-pre-finally-label) -----| - // ^ - // |-- ... <-- (4-post-finally-label) <--- (5) - // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account - // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) - // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable - // Simply speaking code inside finally block is treated as reachable as pre-try-flow - // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. - // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from - // final flows of these blocks without taking pre-try flow into account. - // - // extra edges that we inject allows to control this behavior - // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }; + // Possible ways control can reach the finally block: + // 1) Normal completion of try block of a try-finally or try-catch-finally + // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally + // 3) Exception in try block of a try-finally + // 4) Exception in catch block of a try-catch-finally + // When analyzing a control flow graph that starts inside a finally block we want to consider all + // four possibilities above. However, when analyzing a control flow graph that starts outside (past) + // the finally block, we only want to consider the first two (if we're past a finally block then it + // must have completed normally). To make this possible, we inject two extra nodes into the control + // flow graph: An after-finally with an antecedent of the control flow at the end of the finally + // block, and a pre-finally with an antecedent that represents all exceptional control flows. The + // 'lock' property of the pre-finally references the after-finally, and the after-finally has a + // boolean 'locked' property that we set to true when analyzing a control flow that contained the + // the after-finally node. When the lock associated with a pre-finally is locked, the antecedent of + // the pre-finally (i.e. the exceptional control flows) are skipped. + var preFinallyFlow = initFlowNode({ flags: 4096 /* PreFinally */, antecedent: exceptionTarget, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); - // if flow after finally is unreachable - keep it - // otherwise check if flows after try and after catch are unreachable - // if yes - convert current flow to unreachable - // i.e. - // try { return "1" } finally { console.log(1); } - // console.log(2); // this line should be unreachable even if flow falls out of finally block + // If the end of the finally block is reachable, but the end of the try and catch blocks are not, + // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should + // result in an unreachable current control flow. if (!(currentFlow.flags & 1 /* Unreachable */)) { if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow @@ -29962,7 +30181,7 @@ var ts; } } if (!(currentFlow.flags & 1 /* Unreachable */)) { - var afterFinallyFlow = flowNodeCreated({ flags: 8192 /* AfterFinally */, antecedent: currentFlow }); + var afterFinallyFlow = initFlowNode({ flags: 8192 /* AfterFinally */, antecedent: currentFlow }); preFinallyFlow.lock = afterFinallyFlow; currentFlow = afterFinallyFlow; } @@ -29996,6 +30215,7 @@ var ts; var savedSubtreeTransformFlags = subtreeTransformFlags; subtreeTransformFlags = 0; var clauses = node.clauses; + var isNarrowingSwitch = isNarrowingExpression(node.parent.expression); var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { var clauseStart = i; @@ -30004,14 +30224,14 @@ var ts; i++; } var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; @@ -30075,7 +30295,7 @@ var ts; } function bindAssignmentTargetFlow(node) { if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); + currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } else if (node.kind === 191 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { @@ -30156,7 +30376,7 @@ var ts; if (operator === 62 /* EqualsToken */ && node.left.kind === 194 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } } @@ -30192,7 +30412,7 @@ var ts; } } else { - currentFlow = createFlowAssignment(currentFlow, node); + currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } } function bindVariableDeclarationFlow(node) { @@ -30214,12 +30434,9 @@ var ts; addDeclarationToSymbol(host.symbol, host, 32 /* Class */); } } - function isOutermostOptionalChain(node) { - return !ts.isOptionalChain(node.parent) || ts.isOptionalChainRoot(node.parent) || node !== node.parent.expression; - } function bindOptionalExpression(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); - if (!ts.isOptionalChain(node) || isOutermostOptionalChain(node)) { + if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -30257,7 +30474,7 @@ var ts; currentFlow = finishFlowLabel(preChainLabel); } doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget); - if (isOutermostOptionalChain(node)) { + if (ts.isOutermostOptionalChain(node)) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -30301,7 +30518,7 @@ var ts; if (node.expression.kind === 193 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } } @@ -30601,7 +30818,7 @@ var ts; var host = ts.getJSDocHost(typeAlias); container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); var declName = ts.getNameOfDeclaration(typeAlias); @@ -30614,7 +30831,12 @@ var ts; switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: - container = file; + if (!ts.isExternalOrCommonJsModule(file)) { + container = undefined; + } + else { + container = file; + } break; case 4 /* ThisProperty */: container = declName.parent.expression; @@ -30628,7 +30850,9 @@ var ts; case 0 /* None */: return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration"); } - declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + if (container) { + declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + } container = oldContainer; } } @@ -31024,6 +31248,8 @@ var ts; case 302 /* JSDocTypeLiteral */: case 185 /* MappedType */: return bindAnonymousTypeWorker(node); + case 307 /* JSDocClassTag */: + return bindJSDocClassTag(node); case 192 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); case 200 /* FunctionExpression */: @@ -31243,7 +31469,8 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -31259,7 +31486,7 @@ var ts; constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); } } - if (constructorSymbol) { + if (constructorSymbol && constructorSymbol.valueDeclaration) { // Declare a 'member' if the container is an ES5 class or ES6 constructor constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); // It's acceptable for multiple 'this' assignments of the same identifier to occur @@ -31332,6 +31559,10 @@ var ts; } function bindObjectDefinePrototypeProperty(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol) { + // Ensure the namespace symbol becomes class-like + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** @@ -31406,7 +31637,7 @@ var ts; } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); } return namespaceSymbol; @@ -32055,7 +32286,8 @@ var ts; || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type - || !node.body) { + || !node.body + || node.questionToken) { transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax @@ -32092,7 +32324,7 @@ var ts; function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 1048576 /* ContainsClassFields */; // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax. - if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type) { + if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken) { transformFlags |= 1 /* AssertTypeScript */; } // Hoisted variables related to class properties should live within the TypeScript class wrapper. @@ -32897,6 +33129,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 7] = "ResolvedTypeArguments"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -32907,12 +33140,6 @@ var ts; CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; })(CheckMode || (CheckMode = {})); - var ContextFlags; - (function (ContextFlags) { - ContextFlags[ContextFlags["None"] = 0] = "None"; - ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; - ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; - })(ContextFlags || (ContextFlags = {})); var AccessFlags; (function (AccessFlags) { AccessFlags[AccessFlags["None"] = 0] = "None"; @@ -33046,14 +33273,12 @@ var ts; undefinedSymbol.declarations = []; var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); globalThisSymbol.exports = globals; + globalThisSymbol.declarations = []; globals.set(globalThisSymbol.escapedName, globalThisSymbol); var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; - // This object is reused for `checkOptionalExpression` return values to avoid frequent GC due to nursery object allocations. - // This object represents a pool-size of 1. - var pooledOptionalTypeResult = { isOptional: false, type: undefined }; // for public members that accept a Node or one of its subtypes, we must guard against // synthetic nodes created during transformations by calling `getParseTreeNode`. // for most of these, we perform the guard only on `checker` to avoid any possible @@ -33172,9 +33397,9 @@ var ts; }, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (nodeIn) { + getContextualType: function (nodeIn, contextFlags) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); @@ -33223,7 +33448,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments), getAmbientModules: getAmbientModules, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { @@ -33352,10 +33577,10 @@ var ts; var errorType = createIntrinsicType(1 /* Any */, "error"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 262144 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 262144 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -33381,7 +33606,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", 1048576 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -33399,7 +33624,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 |= 1048576 /* NonInferrableType */; + anyFunctionType.objectFlags |= 2097152 /* 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); @@ -33408,10 +33633,10 @@ var ts; markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances var noIterationTypes = { @@ -33564,7 +33789,7 @@ var ts; var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } } } @@ -33574,7 +33799,7 @@ var ts; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -35052,7 +35277,7 @@ var ts; var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0); var symbol; if (name.kind === 75 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { @@ -35164,7 +35389,12 @@ var ts; return undefined; } var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl); - return init && getSymbolOfNode(init) || undefined; + if (init) { + var initSymbol = getSymbolOfNode(init); + if (initSymbol) { + return mergeJSSymbols(initSymbol, symbol); + } + } } function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); @@ -35591,8 +35821,8 @@ var ts; } function findConstructorDeclaration(node) { var members = node.members; - for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { - var member = members_2[_i]; + for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { + var member = members_3[_i]; if (member.kind === 161 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } @@ -36015,7 +36245,7 @@ var ts; // Type Reference or TypeAlias entity = Identifier meaning = 788968 /* Type */; } - var firstIdentifier = getFirstIdentifier(entityName); + var firstIdentifier = ts.getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { @@ -36507,8 +36737,6 @@ var ts; else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && ts.isClassLike(type.symbol.valueDeclaration) && - // Use `import` types for refs to other scopes, only anonymize something defined in the same scope - ts.findAncestor(type.symbol.valueDeclaration, function (d) { return d === ts.getSourceFileOfNode(context.enclosingDeclaration); }) && !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } @@ -36669,9 +36897,9 @@ var ts; } } } - var propertyName = symbolToName(propertySymbol, context, 111551 /* Value */, /*expectsIdentifier*/ true); - context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; + var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */); @@ -36870,7 +37098,7 @@ var ts; if (!context.tracker.trackSymbol) return; // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(accessExpression); + var firstIdentifier = ts.getFirstIdentifier(accessExpression); var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */); @@ -37236,22 +37464,34 @@ var ts; } } } + function isSingleQuotedStringNamed(d) { + var name = ts.getNameOfDeclaration(d); + if (name && ts.isStringLiteral(name) && (name.singleQuote || + (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")))) { + return true; + } + return false; + } function getPropertyNameNodeForSymbol(symbol, context) { - var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context); + var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed); + var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote); if (fromNameType) { return fromNameType; } + if (ts.isKnownSymbol(symbol)) { + return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3))); + } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); - return createPropertyNameNodeForIdentifierOrLiteral(rawName); + return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote); } // See getNameForSymbolFromNameType for a stringy equivalent - function getPropertyNameNodeForSymbolFromNameType(symbol, context) { + function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) { var nameType = symbol.nameType; if (nameType) { if (nameType.flags & 384 /* StringOrNumberLiteral */) { var name = "" + nameType.value; if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { - return ts.createLiteral(name); + return ts.createLiteral(name, !!singleQuote); } if (isNumericLiteralName(name) && ts.startsWith(name, "-")) { return ts.createComputedPropertyName(ts.createLiteral(+name)); @@ -37263,8 +37503,8 @@ var ts; } } } - function createPropertyNameNodeForIdentifierOrLiteral(name) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name); + function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -37304,7 +37544,7 @@ var ts; var visitedSymbols = ts.createMap(); var deferredPrivates; var oldcontext = context; - context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.mapMap(symbolTable, function (_symbol, name) { return [ts.unescapeLeadingUnderscores(name), true]; }), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { + context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it @@ -37322,6 +37562,10 @@ var ts; context.usedSymbolNames.set(name, true); }); } + ts.forEachEntry(symbolTable, function (symbol, name) { + var baseName = ts.unescapeLeadingUnderscores(name); + void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames` + }); var addingDeclare = !bundled; var exportEquals = symbolTable.get("export=" /* ExportEquals */); if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) { @@ -37513,7 +37757,11 @@ var ts; isPrivate = true; } var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0); - if (symbol.flags & 16 /* Function */) { + var isConstMergedWithNS = symbol.flags & 1536 /* Module */ && + symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && + symbol.escapedName !== "export=" /* ExportEquals */; + var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol); + if (symbol.flags & 16 /* Function */ || isConstMergedWithNSPrintableAsSignatureMerge) { serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } if (symbol.flags & 524288 /* TypeAlias */) { @@ -37524,7 +37772,8 @@ var ts; if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) - && !(symbol.flags & 32 /* Class */)) { + && !(symbol.flags & 32 /* Class */) + && !isConstMergedWithNSPrintableAsSignatureMerge) { serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags); } if (symbol.flags & 384 /* Enum */) { @@ -37541,7 +37790,7 @@ var ts; serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } } - if (symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */)) { + if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) { serializeModule(symbol, symbolName, modifierFlags); } if (symbol.flags & 64 /* Interface */) { @@ -37569,7 +37818,10 @@ var ts; } } function includePrivateSymbol(symbol) { + if (ts.some(symbol.declarations, ts.isParameterDeclaration)) + return; ts.Debug.assertDefined(deferredPrivates); + getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol deferredPrivates.set("" + getSymbolId(symbol), symbol); } function isExportingScope(enclosingDeclaration) { @@ -37628,8 +37880,14 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } + function getNamespaceMembersForSerialization(symbol) { + return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + } + function isTypeOnlyNamespace(symbol) { + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); }); + } function serializeModule(symbol, symbolName, modifierFlags) { - var members = !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + var members = getNamespaceMembersForSerialization(symbol); // Split NS members up by declaration - members whose parent symbol is the ns symbol vs those whose is not (but were added in later via merging) var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; }); var realMembers = locationMap.get("real") || ts.emptyArray; @@ -37639,17 +37897,20 @@ var ts; // so we don't even have placeholders to fill in. if (ts.length(realMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, /*suppressNewPrivateContext*/ false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); } if (ts.length(mergedMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - ts.forEach(mergedMembers, includePrivateSymbol); var nsBody = ts.createModuleBlock([ts.createExportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); - return ts.createExportSpecifier(name === localName ? undefined : localName, name); + var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); + includePrivateSymbol(target || s); + var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; + return ts.createExportSpecifier(name === targetName ? undefined : targetName, name); })))]); addResult(ts.createModuleDeclaration( /*decorators*/ undefined, @@ -37850,7 +38111,11 @@ var ts; case 254 /* ImportClause */: addResult(ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), + // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned + // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag + // In such cases, the `target` refers to the module itself already + ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 255 /* NamespaceImport */: addResult(ts.createImportDeclaration( @@ -37862,7 +38127,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([ ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName)) - ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 261 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, @@ -37876,6 +38141,7 @@ var ts; serializeMaybeAliasAssignment(symbol); break; case 208 /* BinaryExpression */: + case 193 /* PropertyAccessExpression */: // Could be best encoded as though an export specifier or as though an export assignment // If name is default or export=, do an export assignment // Otherwise do an export specifier @@ -37886,10 +38152,6 @@ var ts; serializeExportSpecifier(localName, targetName); } break; - case 193 /* PropertyAccessExpression */: - // A PAE alias is _always_ going to exist as an append to a top-level export, where our top level - // handling should always be sufficient to encode the export action itself - break; default: return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!"); } @@ -37913,7 +38175,8 @@ var ts; var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol); // serialize what the alias points to, preserve the declaration's initializer var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); - if (target) { + // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const + if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) { // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it // eg, `namespace A { export class B {} }; exports = A.B;` // Technically, this is all that's required in the case where the assignment is an entity name expression @@ -37988,6 +38251,7 @@ var ts; return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) && !getIndexInfoOfType(typeToSerialize, 0 /* String */) && !getIndexInfoOfType(typeToSerialize, 1 /* Number */) && + !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK !getDeclarationWithTypeAnnotation(hostSymbol) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && @@ -38131,7 +38395,7 @@ var ts; return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = getFirstIdentifier(node); + var leftmost = ts.getFirstIdentifier(node); var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); if (sym) { includePrivateSymbol(sym); @@ -38261,11 +38525,8 @@ var ts; return context.remappedSymbolNames.get("" + getSymbolId(symbol)); } } - if (input === "default" /* Default */) { - input = "_default"; - } - else if (input === "export=" /* ExportEquals */) { - input = "_exports"; + if (symbol) { + input = getNameCandidateWorker(symbol, input); } var i = 0; var original = input; @@ -38279,17 +38540,28 @@ var ts; } return input; } - function getInternalSymbolName(symbol, localName) { - if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) { - return context.remappedSymbolNames.get("" + getSymbolId(symbol)); - } + function getNameCandidateWorker(symbol, localName) { if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) { var flags = context.flags; context.flags |= 16777216 /* InInitialEntityName */; var nameCandidate = getNameOfSymbolAsWritten(symbol, context); context.flags = flags; - localName = ts.isIdentifierText(nameCandidate, languageVersion) && !ts.isStringANonContextualKeyword(nameCandidate) ? nameCandidate : getUnusedName("_default", symbol); + localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate; } + if (localName === "default" /* Default */) { + localName = "_default"; + } + else if (localName === "export=" /* ExportEquals */) { + localName = "_exports"; + } + localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_"); + return localName; + } + function getInternalSymbolName(symbol, localName) { + if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) { + return context.remappedSymbolNames.get("" + getSymbolId(symbol)); + } + localName = getNameCandidateWorker(symbol, localName); // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up context.remappedSymbolNames.set("" + getSymbolId(symbol), localName); return localName; @@ -38554,7 +38826,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); + var firstIdentifier = ts.getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); var id = importSymbol && "" + getSymbolId(importSymbol); if (importSymbol && !visited.has(id)) { @@ -38618,6 +38890,8 @@ var ts; return !!target.immediateBaseConstraint; case 6 /* JSDocTypeReference */: return !!getSymbolLinks(target).resolvedJSDocType; + case 7 /* ResolvedTypeArguments */: + return !!target.resolvedTypeArguments; } return ts.Debug.assertNever(propertyName); } @@ -38703,7 +38977,9 @@ var ts; } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); - return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + result.objectFlags |= 131072 /* ObjectRestType */; + return result; } // Determine the control flow type associated with a destructuring declaration or assignment. The following // forms of destructuring are possible: @@ -39089,23 +39365,23 @@ var ts; kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); - var members_3 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_3); + var members_4 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_3.has(name)) { + if (members_4.has(name)) { var exportedMember = exportedType_1.members.get(name); var union = createSymbol(s.flags | exportedMember.flags, name); union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_3.set(name, union); + members_4.set(name, union); } else { - members_3.set(name, s); + members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag return result; } @@ -39165,7 +39441,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -39305,16 +39581,12 @@ var ts; if (!declaration.statements.length) { return emptyObjectType; } - var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); - if (type_1.flags & 524288 /* Object */) { - return getRegularTypeOfObjectLiteral(type_1); - } - return type_1; + return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression))); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39382,7 +39654,7 @@ var ts; } if (!popTypeResolution()) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39465,7 +39737,9 @@ var ts; } else { ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -39511,11 +39785,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_2; + return type_1; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -39701,6 +39975,7 @@ var ts; // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 245 /* InterfaceDeclaration */); + ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -39731,7 +40006,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length === 1) { var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -40438,8 +40713,8 @@ var ts; var decl = _a[_i]; var members = ts.getMembersOfDeclaration(decl); if (members) { - for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { - var member = members_4[_b]; + for (var _b = 0, members_5 = members; _b < members_5.length; _b++) { + var member = members_5[_b]; if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { lateBindMember(symbol, earlySymbols, lateSymbols, member); } @@ -40568,8 +40843,8 @@ var ts; var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + var sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -40577,15 +40852,13 @@ var ts; sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; } function cloneSignature(sig) { var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -40597,13 +40870,25 @@ var ts; result.mapper = undefined; return result; } - function createOptionalCallSignature(signature) { + function getOptionalCallSignature(signature, callChainFlags) { + if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) { + return signature; + } + if (!signature.optionalCallSignatureCache) { + signature.optionalCallSignatureCache = {}; + } + var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer"; + return signature.optionalCallSignatureCache[key] + || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags)); + } + function createOptionalCallSignature(signature, callChainFlags) { + ts.Debug.assert(callChainFlags === 4 /* IsInnerCallChain */ || callChainFlags === 8 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both."); var result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= callChainFlags; return result; } function getExpandedParameters(sig) { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { var restIndex_1 = sig.parameters.length - 1; var restParameter = sig.parameters[restIndex_1]; var restType = getTypeOfSymbol(restParameter); @@ -40628,7 +40913,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJSFile(baseTypeNode); @@ -40792,11 +41077,9 @@ var ts; var params = combineUnionParameters(left, right); var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - var hasRestParam = left.hasRestParameter || right.hasRestParameter; - var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */); result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); return result; } @@ -40969,7 +41252,7 @@ var ts; var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray; if (symbol.flags & 16 /* Function */) { constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) : undefined; })); } if (!constructSignatures.length) { @@ -41475,8 +41758,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_3 = types_6[_i]; - var baseType = getBaseConstraint(type_3); + var type_2 = types_6[_i]; + var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } @@ -41909,7 +42192,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var flags = 0 /* None */; var minArgumentCount = 0; var thisParameter = void 0; var hasThisParameter = false; @@ -41940,7 +42223,7 @@ var ts; parameters.push(paramSymbol); } if (type && type.kind === 186 /* LiteralType */) { - hasLiteralTypes = true; + flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || @@ -41966,9 +42249,11 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1 /* HasRestParameter */; + } links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, - /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -42111,8 +42396,11 @@ var ts; signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, /*wasOptional*/ true); + if (signature.flags & 4 /* IsInnerCallChain */) { + type = addOptionalTypeMarker(type); + } + else if (signature.flags & 8 /* IsOuterCallChain */) { + type = getOptionalType(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -42168,7 +42456,7 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, 1 /* Number */); @@ -42385,7 +42673,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 1835008 /* PropagatingFlags */; + return result & 3670016 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -42419,13 +42707,25 @@ var ts; return type; } function getTypeArguments(type) { + var _a, _b; if (!type.resolvedTypeArguments) { + if (!pushTypeResolution(type, 7 /* ResolvedTypeArguments */)) { + return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray; + } var node = type.node; var typeArguments = !node ? ts.emptyArray : node.kind === 168 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : node.kind === 173 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode); - type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + if (popTypeResolution()) { + type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + } + else { + type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray; + error(type.node || currentNode, type.target.symbol + ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves + : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol)); + } } return type.resolvedTypeArguments; } @@ -42542,7 +42842,7 @@ var ts; errorType; } if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) { - var jsdocType = getTypeFromJSAlias(node, symbol); + var jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -42555,18 +42855,30 @@ var ts; return errorType; } /** - * A JSdoc TypeReference may be to a value imported from commonjs. - * These should really be aliases, but this special-case code fakes alias resolution - * by producing a type from a value. + * A JSdoc TypeReference may be to a value, but resolve it as a type anyway. + * Note: If the value is imported from commonjs, it should really be an alias, + * but this function's special-case code fakes alias resolution as well. */ - function getTypeFromJSAlias(node, symbol) { + function getTypeFromJSDocValueReference(node, symbol) { var valueType = getTypeOfSymbol(symbol); - var typeType = valueType.symbol && - valueType.symbol !== symbol && // Make sure this is a commonjs export by checking that symbol -> type -> symbol doesn't roundtrip. - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + var typeType = valueType; + if (symbol.valueDeclaration) { + var decl = ts.getRootDeclaration(symbol.valueDeclaration); + var isRequireAlias = false; + if (ts.isVariableDeclaration(decl) && decl.initializer) { + var expr = decl.initializer; + // skip past entity names, eg `require("x").a.b.c` + while (ts.isPropertyAccessExpression(expr)) { + expr = expr.expression; + } + isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol; + } + var isImportTypeWithQualifier = node.kind === 187 /* ImportType */ && node.qualifier; + if (isRequireAlias || isImportTypeWithQualifier) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable, substitute) { if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === typeVariable) { @@ -42995,7 +43307,7 @@ var ts; if (type === wildcardType) includes |= 4194304 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 262144 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) includes |= 2097152 /* IncludesNonWideningType */; } else { @@ -43122,7 +43434,7 @@ var ts; neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 131072 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -43272,7 +43584,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) & 131072 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -43281,7 +43593,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 131072 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -43310,7 +43622,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 131072 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -44107,7 +44419,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host)) { + while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 137 /* ReadonlyKeyword */) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -44208,7 +44520,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ @@ -44522,7 +44834,7 @@ var ts; // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */); result.target = signature; result.mapper = mapper; return result; @@ -45403,20 +45715,20 @@ var ts; } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, - /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */; } /** * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any` */ function isAnySignature(s) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } /** * See signatureRelatedTo, compareSignaturesIdentical */ - function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) { // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; @@ -45435,6 +45747,9 @@ var ts; var sourceCount = getParameterCount(source); var sourceRestType = getNonArrayRestType(source); var targetRestType = getNonArrayRestType(target); + if (sourceRestType || targetRestType) { + void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers); + } if (sourceRestType && targetRestType && sourceCount !== targetCount) { // We're not able to relate misaligned complex rest parameters return 0 /* False */; @@ -45478,7 +45793,7 @@ var ts; (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); var related = callbacks ? // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is - compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) : + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { @@ -45492,13 +45807,13 @@ var ts; // If a signature resolution is already in-flight, skip issuing a circularity error // here and just use the `any` type directly var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType - : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(target.declaration.symbol) + : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol)) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType - : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(source.declaration.symbol) + : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol)) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); @@ -45685,7 +46000,7 @@ var ts; return true; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var related = relation.get(getRelationKey(source, target, relation)); + var related = relation.get(getRelationKey(source, target, /*isIntersectionConstituent*/ false, relation)); if (related !== undefined) { return !!(related & 1 /* Succeeded */); } @@ -46056,7 +46371,7 @@ var ts; // and we need to handle "each" relations before "some" relations for the same kind of type. if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), isIntersectionConstituent) : + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); } else { @@ -46094,7 +46409,7 @@ var ts; // // - For a primitive type or type parameter (such as 'number = A & B') there is no point in // breaking the intersection apart. - result = someTypeRelatedToType(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ true); + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { @@ -46207,7 +46522,7 @@ var ts; // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) - if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration)) { + if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) { // Note that extraneous children (as in `extra`) don't pass this check, // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute. errorNode = prop.valueDeclaration.name; @@ -46218,7 +46533,7 @@ var ts; // use the property's value declaration if the property is assigned inside the literal itself var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; - if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) { var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; @@ -46378,14 +46693,14 @@ var ts; } return result; } - function someTypeRelatedToType(source, target, reportErrors, isIntersectionConstituent) { + function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; for (var i = 0; i < len; i++) { - var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, isIntersectionConstituent); + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { return related; } @@ -46473,7 +46788,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, relation); + var id = getRelationKey(source, target, isIntersectionConstituent, relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -47367,7 +47682,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, incompatibleReporter, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, incompatibleReporter, isRelatedTo, reportUnreliableMarkers); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -47659,17 +47974,18 @@ var ts; * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. * For other cases, the types ids are used. */ - function getRelationKey(source, target, relation) { + function getRelationKey(source, target, isIntersectionConstituent, relation) { if (relation === identityRelation && source.id > target.id) { var temp = source; source = target; target = temp; } + var intersection = isIntersectionConstituent ? "&" : ""; if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { var typeParameters = []; - return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + intersection; } - return source.id + "," + target.id; + return source.id + "," + target.id + intersection; } // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. @@ -47720,7 +48036,7 @@ var ts; // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`). function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 524288 /* Object */) { + if (depth >= 5 && type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { var symbol = type.symbol; if (symbol) { var count = 0; @@ -48095,37 +48411,19 @@ var ts; function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type) { + return type !== optionalType; + } function removeOptionalTypeMarker(type) { - return strictNullChecks ? filterType(type, function (t) { return t !== optionalType; }) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } - function propagateOptionalTypeMarker(type, wasOptional) { - return wasOptional ? addOptionalTypeMarker(type) : type; + function propagateOptionalTypeMarker(type, node, wasOptional) { + return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional, type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - function checkOptionalExpression(parent, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var isOptional = false; - var type = checkExpression(expression); - if (ts.isOptionalChain(parent)) { - if (parent.questionDotToken) { - // If we have a questionDotToken then we are an OptionalExpression and should remove `null` and - // `undefined` from the type and add the optionalType to the result, if needed. - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - // If we do not have a questionDotToken, then we are an OptionalChain and we remove the optionalType and - // indicate whether we need to add optionalType back into the result. - var nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType, expression) { + return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } /** * Is source potentially coercible to target type under `==`. @@ -48279,14 +48577,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 */ | 1048576 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* 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) & 786432 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -48331,7 +48629,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 262144 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -48357,7 +48655,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) & 262144 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -48437,7 +48735,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 262144 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -48554,7 +48852,7 @@ var ts; return !!(type.flags & 63176704 /* Instantiable */ || 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 */ || + objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { @@ -48609,7 +48907,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) & 1048576 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }); } function createReverseMappedType(source, target, constraint) { @@ -48760,10 +49058,7 @@ var ts; // inferring a type parameter constraint. Instead, make a lower priority inference from // the full source to whatever remains in the target. For example, when inferring from // string to 'string | T', make a lower priority inference of string for T. - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, 1 /* NakedTypeVariable */); return; } source = getUnionType(sources); @@ -48796,7 +49091,7 @@ 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) & 1048576 /* NonInferrableType */ || source === silentNeverType || (priority & 16 /* ReturnType */ && (source === autoType || source === autoArrayType))) { + if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === silentNeverType || (priority & 16 /* ReturnType */ && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -48863,10 +49158,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - var savePriority = priority; - priority |= 32 /* LiteralKeyof */; - inferFromTypes(empty, target.type); - priority = savePriority; + inferWithPriority(empty, target.type, 32 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -48918,6 +49210,12 @@ var ts; } } } + function inferWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -48983,6 +49281,18 @@ var ts; } return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types) { + var typeVariable; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var type = types_13[_i]; + var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } function inferToMultipleTypes(source, targets, targetFlags) { var typeVariableCount = 0; if (targetFlags & 1048576 /* Union */) { @@ -49012,6 +49322,16 @@ var ts; } } } + if (typeVariableCount === 0) { + // If every target is an intersection of types containing a single naked type variable, + // make a lower priority inference to that type variable. This handles inferring from + // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T. + var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */); + } + return; + } // If the target has a single naked type variable and no inference circularities were // encountered above (meaning we explored the types fully), create a union of the source // types from which no inferences have been made so far and infer from that union to the @@ -49043,15 +49363,12 @@ var ts; // we want to infer string for T, not Promise | string. For intersection types // we only infer to single naked type variables. if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) { - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) { var t = targets_4[_b]; if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, 1 /* NakedTypeVariable */); } } - priority = savePriority; } } function inferToMappedType(source, target, constraintType) { @@ -49072,14 +49389,12 @@ var ts; if (inference && !inference.isFixed) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - var savePriority = priority; // 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). - priority |= ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? - 4 /* PartialHomomorphicMappedType */ : 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? + 4 /* PartialHomomorphicMappedType */ : + 2 /* HomomorphicMappedType */); } } return true; @@ -49087,10 +49402,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. - var savePriority = priority; - priority |= 8 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, 8 /* 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 @@ -49199,7 +49511,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 1048576 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -49468,6 +49780,15 @@ var ts; } return false; } + function optionalChainContainsReference(source, target) { + while (ts.isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property // a possible discriminant if its type differs in the constituents of containing union type, and if every @@ -49588,8 +49909,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; result |= getTypeFacts(t); } return result; @@ -49958,8 +50279,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -50040,9 +50361,18 @@ var ts; // expressions are potential type predicate function calls. In order to avoid triggering // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. - var funcType = node.parent.kind === 225 /* ExpressionStatement */ ? getTypeOfDottedName(node.expression, /*diagnostic*/ undefined) : - node.expression.kind !== 101 /* SuperKeyword */ ? checkOptionalExpression(node, node.expression).type : - undefined; + var funcType = void 0; + if (node.parent.kind === 225 /* ExpressionStatement */) { + funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); + } + else if (node.expression.kind !== 101 /* SuperKeyword */) { + if (ts.isOptionalChain(node)) { + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */); var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -50055,6 +50385,13 @@ var ts; return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */); } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { + return callExpression.arguments[predicate.parameterIndex]; + } + var invokedExpression = ts.skipParentheses(callExpression.expression); + return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined; + } function reportFlowControlError(node) { var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); var sourceFile = ts.getSourceFileOfNode(node); @@ -50070,6 +50407,11 @@ var ts; function isUnlockedReachableFlowNode(flow) { return !(flow.flags & 4096 /* PreFinally */ && flow.lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); } + function isFalseExpression(expr) { + var node = ts.skipParentheses(expr); + return node.kind === 90 /* FalseKeyword */ || node.kind === 208 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); + } function isReachableFlowNodeWorker(flow, noCacheCheck) { while (true) { if (flow === lastFlowNode) { @@ -50089,8 +50431,17 @@ var ts; } else if (flags & 512 /* Call */) { var signature = getEffectsSignature(flow.node); - if (signature && getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { - return false; + if (signature) { + var predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3 /* AssertsIdentifier */) { + var predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { + return false; + } } flow = flow.antecedent; } @@ -50324,6 +50675,9 @@ var ts; } function narrowTypeByAssertion(type, expr) { var node = ts.skipParentheses(expr); + if (node.kind === 90 /* FalseKeyword */) { + return unreachableNeverType; + } if (node.kind === 208 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); @@ -50342,7 +50696,7 @@ var ts; var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : - predicate.kind === 3 /* AssertsIdentifier */ ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -50413,17 +50767,24 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } else if (expr.kind === 203 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); + } + else if (expr.kind === 203 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -50431,6 +50792,7 @@ var ts; var antecedentTypes = []; var subtypeReduction = false; var seenIncomplete = false; + var bypassFlow; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; if (antecedent.flags & 4096 /* PreFinally */ && antecedent.lock.locked) { @@ -50439,6 +50801,11 @@ var ts; // in this case we should ignore this branch. continue; } + if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) { + // The antecedent is the bypass branch of a potentially exhaustive switch statement. + bypassFlow = antecedent; + continue; + } var flowType = getTypeAtFlowNode(antecedent); var type = getTypeFromFlowType(flowType); // If the type at a particular antecedent path is the declared type and the @@ -50459,6 +50826,25 @@ var ts; seenIncomplete = true; } } + if (bypassFlow) { + var flowType = getTypeAtFlowNode(bypassFlow); + var type = getTypeFromFlowType(flowType); + // If the bypass flow contributes a type we haven't seen yet and the switch statement + // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase + // the risk of circularities, we only want to perform them when they make a difference. + if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) { + if (type === declaredType && declaredType === initialType) { + return type; + } + antecedentTypes.push(type); + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + } return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { @@ -50565,6 +50951,9 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } @@ -50613,6 +51002,14 @@ var ts; if (isMatchingReference(reference, right_1)) { return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + } + else if (optionalChainContainsReference(right_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left_1, declaredType)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } @@ -50636,6 +51033,15 @@ var ts; } return type; } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + // We are in a branch of obj?.foo === value or obj?.foo !== value. We remove undefined and null from + // the type of obj if (a) the operator is === and the type of value doesn't include undefined or (b) the + // operator is !== and the type of value is undefined. + var effectiveTrue = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */ ? assumeTrue : !assumeTrue; + var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */; + var valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? 262144 /* EQUndefinedOrNull */ : 65536 /* EQUndefined */)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* Any */) { return type; @@ -50683,8 +51089,14 @@ var ts; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands + if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, target)) { @@ -50692,9 +51104,6 @@ var ts; } return type; } - if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } @@ -50727,6 +51136,10 @@ var ts; return type; } } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { + var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify // values with unit types, except for the case where @@ -50859,6 +51272,9 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' // references might reference a different 'y' property. However, we make an exception @@ -50931,39 +51347,28 @@ var ts; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + var predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (ts.isAccessExpression(invokedExpression) && predicate.type) { - var possibleReference = ts.skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if (ts.isOptionalChainRoot(expr.parent) || + if (ts.isExpressionOfOptionalChainRoot(expr) || ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -51244,7 +51649,24 @@ var ts; } } else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { - error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + var diag = error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // See GH:32846 - if the user is using a variable whose type is () => T1 | ... | undefined + // they may have meant to specify the type as (() => T1 | ...) | undefined + // This is assumed if: the type is a FunctionType, the return type is a Union, the last constituent of + // the union is `undefined` + if (type.symbol && type.symbol.declarations.length === 1 && ts.isFunctionTypeNode(type.symbol.declarations[0])) { + var funcTypeNode = type.symbol.declarations[0]; + var returnType = getReturnTypeFromAnnotation(funcTypeNode); + if (returnType && returnType.flags & 1048576 /* Union */) { + var unionTypes_3 = funcTypeNode.type.types; + if (unionTypes_3 && unionTypes_3[unionTypes_3.length - 1].kind === 145 /* UndefinedKeyword */) { + var parenedFuncType = ts.getMutableClone(funcTypeNode); + // Highlight to the end of the second to last constituent of the union + parenedFuncType.end = unionTypes_3[unionTypes_3.length - 2].end; + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(parenedFuncType, ts.Diagnostics.Did_you_mean_to_parenthesize_this_function_type)); + } + } + } // Return the declared type to reduce follow-on errors return type; } @@ -52024,18 +52446,22 @@ var ts; return undefined; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget, arg) { + function getContextualTypeForArgument(callTarget, arg, contextFlags) { var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + function getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & 4 /* Completion */ && signature.target) { + var baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { @@ -52394,7 +52820,7 @@ var ts; } /* falls through */ case 196 /* NewExpression */: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case 198 /* TypeAssertionExpression */: case 216 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); @@ -52609,8 +53035,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -52711,7 +53137,7 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; } return literalType; } @@ -52848,7 +53274,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 1835008 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -52957,7 +53383,7 @@ 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 */ | 524288 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { result.objectFlags |= 16384 /* JSLiteral */; } @@ -53055,7 +53481,7 @@ var ts; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 1835008 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -53135,7 +53561,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 */ | 524288 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -53607,8 +54033,8 @@ var ts; function symbolHasNonMethodDeclaration(symbol) { return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } - function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */); @@ -53616,22 +54042,34 @@ var ts; function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + function reportObjectPossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + } + function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? - (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + reportError(node, kind); var t = getNonNullableType(type); return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) { @@ -53640,10 +54078,16 @@ var ts; return nonNullType; } function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + function checkPropertyAccessChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); } function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node) { while (node.parent.kind === 199 /* ParenthesizedExpression */) { @@ -53651,8 +54095,7 @@ var ts; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var _a = checkOptionalExpression(node, left), isOptional = _a.isOptional, leftType = _a.type; + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -53705,7 +54148,7 @@ var ts; } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { // Only compute control flow type if this is a property access expression that isn't an @@ -54027,7 +54470,15 @@ var ts; return false; } function checkIndexedAccess(node) { - var _a = checkOptionalExpression(node, node.expression), isOptional = _a.isOptional, exprType = _a.type; + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + function checkElementAccessChain(node) { + var exprType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -54043,7 +54494,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -54114,7 +54565,7 @@ var ts; // interface B extends A { (x: 'foo'): string } // const b: B; // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] - function reorderCandidates(signatures, result, isOptionalCall) { + function reorderCandidates(signatures, result, callChainFlags) { var lastParent; var lastSymbol; var cutoffIndex = 0; @@ -54144,7 +54595,7 @@ var ts; lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -54155,7 +54606,7 @@ var ts; else { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature); } } function isSpreadArgument(arg) { @@ -54239,7 +54690,7 @@ var ts; // the declared number of type parameters, the call has an incorrect arity. var numTypeParameters = ts.length(signature.typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - return !typeArguments || + return !ts.some(typeArguments) || (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. @@ -54450,7 +54901,19 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var thisArgumentType = void 0; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (ts.isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -54677,7 +55140,7 @@ var ts; 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.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_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 (min < argCount && argCount < max) { @@ -54733,7 +55196,7 @@ var ts; } return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } - function resolveCall(node, signatures, candidatesOutArray, checkMode, isOptionalCall, fallbackError) { + function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { var isTaggedTemplate = node.kind === 197 /* TaggedTemplateExpression */; var isDecorator = node.kind === 156 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -54748,7 +55211,7 @@ var ts; } var candidates = candidatesOutArray || []; // reorderCandidates fills up the candidates array directly - reorderCandidates(signatures, candidates, isOptionalCall); + reorderCandidates(signatures, candidates, callChainFlags); if (!candidates.length) { if (reportErrors) { diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); @@ -54910,7 +55373,7 @@ var ts; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) { @@ -54928,7 +55391,7 @@ var ts; var inferenceContext = void 0; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - if (typeArguments) { + if (ts.some(typeArguments)) { typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); if (!typeArgumentTypes) { candidateForTypeArgumentError = candidate; @@ -55003,34 +55466,34 @@ var ts; var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; var _loop_15 = function (i) { - var symbols = ts.mapDefined(candidates, function (_a) { - var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; - return hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : - i < parameters.length ? parameters[i] : undefined; - }); + var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined; }); ts.Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { _loop_15(i); } - var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); - var hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); + var flags = 0 /* None */; + if (restParameterSymbols.length !== 0) { var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1 /* HasRestParameter */; + } + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2 /* HasLiteralTypes */; } return createSignature(candidates[0].declaration, /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. thisParameter, parameters, /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), - /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, - /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + /*typePredicate*/ undefined, minArgumentCount, flags); } function getNumNonRestParameters(signature) { var numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); @@ -55106,12 +55569,24 @@ var ts; var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */); } } return resolveUntypedCall(node); } - var _b = checkOptionalExpression(node, node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined), isOptional = _b.isOptional, funcType = _b.type; + var callChainFlags; + var funcType = checkExpression(node.expression); + if (ts.isCallChain(node)) { + var nonOptionalType = getOptionalExpressionType(funcType, node.expression); + callChainFlags = nonOptionalType === funcType ? 0 /* None */ : + ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ : + 4 /* IsInnerCallChain */; + funcType = nonOptionalType; + } + else { + callChainFlags = 0 /* None */; + } + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -55177,7 +55652,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, isOptional); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags); } function isGenericFunctionReturningFunction(signature) { return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature))); @@ -55240,7 +55715,7 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */); } // If expressionType's apparent type is an object type with no construct signatures but // one or more call signatures, the expression is processed as a function call. A compile-time @@ -55248,7 +55723,7 @@ var ts; // operation is Any. It is an error to have a Void this type. var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); if (!noImplicitAny) { if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); @@ -55333,8 +55808,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var constituent = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var constituent = types_17[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -55425,7 +55900,7 @@ var ts; invocationError(node.tag, apparentType, 0 /* Call */); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); } /** * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. @@ -55478,7 +55953,7 @@ var ts; invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage); } function createSignatureForJSXIntrinsic(node, result) { var namespace = getJsxNamespaceAt(node); @@ -55493,9 +55968,7 @@ var ts; return createSignature(declaration, /*typeParameters*/ undefined, /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, - /*returnTypePredicate*/ undefined, 1, - /*hasRestparameter*/ false, - /*hasLiteralTypes*/ false); + /*returnTypePredicate*/ undefined, 1, 0 /* None */); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -55518,7 +55991,7 @@ var ts; error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); return resolveErrorCall(node); } - return resolveCall(node, signatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */); } /** * Sometimes, we have a decorator that could accept zero arguments, @@ -55528,7 +56001,7 @@ var ts; function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } @@ -55599,7 +56072,7 @@ var ts; return false; } function mergeJSSymbols(target, source) { - if (source && (ts.hasEntries(source.exports) || ts.hasEntries(source.members))) { + if (source) { var links = getSymbolLinks(source); if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) { var inferred = isTransientSymbol(target) ? target : cloneSymbol(target); @@ -55909,7 +56382,7 @@ var ts; return type; } function getParameterNameAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -55926,11 +56399,11 @@ var ts; return tryGetTypeAtPosition(signature, pos) || anyType; } function tryGetTypeAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // We want to return the value undefined for an out of bounds parameter position, // so we need to check bounds here before calling getIndexedAccessType (which // otherwise would return the type 'undefined'). @@ -55965,7 +56438,7 @@ var ts; } function getParameterCount(signature) { var length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -55974,7 +56447,7 @@ var ts; return length; } function getMinArgumentCount(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { var minLength = restType.target.minLength; @@ -55986,14 +56459,14 @@ var ts; return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } return false; } function getEffectiveRestType(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -56010,7 +56483,7 @@ var ts; return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, inferenceContext) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -56043,7 +56516,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } } - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56051,7 +56524,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56328,8 +56801,8 @@ var ts; var witnesses = getSwitchClauseTypeOfWitnesses(node); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_4 = getBaseConstraintOfType(operandType) || operandType; - return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + var type_3 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -56456,9 +56929,9 @@ var ts; return links.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + 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 |= 1048576 /* NonInferrableType */; + returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } return anyFunctionType; @@ -56687,8 +57160,7 @@ var ts; var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); var func = ts.getContainingFunction(node); - if (func && func.kind !== 161 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + if (func && func.kind !== 161 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -56789,8 +57261,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -57424,25 +57896,10 @@ var ts; } return [effectiveLeft, effectiveRight]; } - function isYieldExpressionInClass(node) { - var current = node; - var parent = node.parent; - while (parent) { - if (ts.isFunctionLike(parent) && current === parent.body) { - return false; - } - else if (ts.isClassLike(current)) { - return true; - } - current = parent; - parent = parent.parent; - } - return false; - } function checkYieldExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 8192 /* YieldContext */) || isYieldExpressionInClass(node)) { + if (!(node.flags & 8192 /* YieldContext */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -57778,6 +58235,18 @@ var ts; } } } + function getReturnTypeOfSingleNonGenericCallSignature(funcType) { + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) { + var funcType = checkExpression(expr.expression); + var nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType); + return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType); + } /** * Returns the type of an expression. Unlike checkExpression, this function is simply concerned * with computing the type and may not fully check all contained sub-expressions for errors. @@ -57789,10 +58258,10 @@ var ts; // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. if (ts.isCallExpression(expr) && expr.expression.kind !== 101 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { - var _a = checkOptionalExpression(expr, expr.expression), isOptional = _a.isOptional, funcType = _a.type; - var signature = getSingleCallSignature(funcType); - if (signature && !signature.typeParameters) { - return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); + var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : + getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression)); + if (type) { + return type; } } else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) { @@ -57842,7 +58311,7 @@ var ts; (node.parent.kind === 194 /* ElementAccessExpression */ && node.parent.expression === node) || ((node.kind === 75 /* Identifier */ || node.kind === 152 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || (node.parent.kind === 171 /* TypeQuery */ && node.parent.exprName === node)) || - (node.parent.kind === 261 /* ExportSpecifier */ && (compilerOptions.preserveConstEnums || node.flags & 8388608 /* Ambient */)); // We allow reexporting const enums + (node.parent.kind === 261 /* ExportSpecifier */); // We allow reexporting const enums if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -58046,7 +58515,7 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -59221,7 +59690,7 @@ var ts; return; } // Verify there is no local declaration that could collide with the promise constructor. - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); @@ -59278,7 +59747,7 @@ var ts; function markEntityNameOrEntityExpressionAsReference(typeName) { if (!typeName) return; - var rootName = getFirstIdentifier(typeName); + var rootName = ts.getFirstIdentifier(typeName); var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol @@ -59318,8 +59787,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var typeNode = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var typeNode = types_19[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -61094,10 +61563,7 @@ var ts; firstDefaultClause = clause; } else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -61118,6 +61584,9 @@ var ts; } } ts.forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -61640,11 +62109,13 @@ var ts; // same when the derived property is from an assignment continue; } - if (basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property; - } - else if (basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor; + var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */; + var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */; + if (overriddenInstanceProperty || overriddenInstanceAccessor) { + var errorMessage_1 = overriddenInstanceProperty ? + ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : + 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 { var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 158 /* PropertyDeclaration */ && !d.initializer; }); @@ -61660,24 +62131,22 @@ var ts; || !ts.isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { - var errorMessage_1 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; - error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType)); + var errorMessage_2 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType)); } } - // correct case - continue; } + // correct case + continue; } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { - // method is overridden with method -- correct case + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { + // method is overridden with method or property -- correct case continue; } - else if (derived.flags & 98304 /* Accessor */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & 98304 /* Accessor */) { @@ -62183,22 +62652,6 @@ var ts; break; } } - function getFirstIdentifier(node) { - switch (node.kind) { - case 75 /* Identifier */: - return node; - case 152 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 75 /* Identifier */); - return node; - case 193 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 75 /* Identifier */); - return node; - } - } function getFirstNonModuleExportsIdentifier(node) { switch (node.kind) { case 75 /* Identifier */: @@ -62328,7 +62781,7 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - var moduleName = getFirstIdentifier(node.moduleReference); + var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } @@ -62395,7 +62848,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -64701,10 +65154,10 @@ var ts; if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -65587,7 +66040,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -65657,6 +66110,14 @@ var ts; case 2 /* Next */: return "nextType"; } } + function signatureHasRestParameter(s) { + return !!(s.flags & 1 /* HasRestParameter */); + } + ts.signatureHasRestParameter = signatureHasRestParameter; + function signatureHasLiteralTypes(s) { + return !!(s.flags & 2 /* HasLiteralTypes */); + } + ts.signatureHasLiteralTypes = signatureHasLiteralTypes; })(ts || (ts = {})); var ts; (function (ts) { @@ -66590,7 +67051,9 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } // Because we are updating existed propertyAccess we want to inherit its emitFlags // instead of using the default from createPropertyAccess return node.expression !== expression @@ -66628,7 +67091,9 @@ var ts; } ts.createElementAccess = createElementAccess; function updateElementAccess(node, expression, argumentExpression) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -66662,7 +67127,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (ts.isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -67264,7 +67731,7 @@ var ts; var node = createSynthesizedNode(231 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -69790,7 +70257,7 @@ var ts; var conditionalPrecedence = ts.getOperatorPrecedence(209 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { return ts.createParen(condition); } return condition; @@ -70388,6 +70855,12 @@ var ts; * Gets the property name of a BindingOrAssignmentElement */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement); + ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element."); + return propertyName; + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { case 190 /* BindingElement */: // `a` in `let { a: b } = ...` @@ -70423,9 +70896,8 @@ var ts; ? target.expression : target; } - ts.Debug.fail("Invalid property name for binding element."); } - ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; function isStringOrNumericLiteral(node) { var kind = node.kind; return kind === 10 /* StringLiteral */ @@ -72444,7 +72916,8 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node)) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); @@ -72513,6 +72986,17 @@ var ts; } return false; } + function bindingOrAssignmentElementContainsNonLiteralComputedName(element) { + var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element); + if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) { + return true; + } + var target = ts.getTargetOfBindingOrAssignmentElement(element); + return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target); + } + function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) { + return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName); + } /** * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * @@ -72543,7 +73027,8 @@ var ts; }; if (ts.isVariableDeclaration(node)) { var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); - if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node))) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); @@ -73842,8 +74327,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { - var member = members_5[_i]; + for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { + var member = members_6[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -74233,8 +74718,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -74846,7 +75331,12 @@ var ts; * * @param node The module declaration node. */ - function shouldEmitModuleDeclaration(node) { + function shouldEmitModuleDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration); + if (!node) { + // If we can't find a parse tree node, assume the node is instantiated. + return true; + } return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } /** @@ -75665,7 +76155,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); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -77422,7 +77912,7 @@ var ts; } return ts.updateParen(node, expression); } - function visitNonOptionalPropertyAccessExpression(node, captureThisArg) { + function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg) { if (ts.isOptionalChain(node)) { // If `node` is an optional chain, then it is the outermost chain of an optional expression. return visitOptionalExpression(node, captureThisArg); @@ -77431,27 +77921,17 @@ var ts; ts.Debug.assertNotNode(expression, ts.isSyntheticReference); var thisArg; if (captureThisArg) { - // `a.b` -> { expression: `(_a = a).b`, thisArg: `_a` } - thisArg = ts.createTempVariable(hoistVariableDeclaration); - expression = ts.createParen(ts.createAssignment(thisArg, expression)); + if (shouldCaptureInTempVariable(expression)) { + thisArg = ts.createTempVariable(hoistVariableDeclaration); + expression = ts.createAssignment(thisArg, expression); + } + else { + thisArg = expression; + } } - expression = ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)); - return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression; - } - function visitNonOptionalElementAccessExpression(node, captureThisArg) { - if (ts.isOptionalChain(node)) { - // If `node` is an optional chain, then it is the outermost chain of an optional expression. - return visitOptionalExpression(node, captureThisArg); - } - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - ts.Debug.assertNotNode(expression, ts.isSyntheticReference); - var thisArg; - if (captureThisArg) { - // `a[b]` -> { expression: `(_a = a)[b]`, thisArg: `_a` } - thisArg = ts.createTempVariable(hoistVariableDeclaration); - expression = ts.createParen(ts.createAssignment(thisArg, expression)); - } - expression = ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); + expression = node.kind === 193 /* PropertyAccessExpression */ + ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) + : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression; } function visitNonOptionalCallExpression(node, captureThisArg) { @@ -77464,8 +77944,8 @@ var ts; function visitNonOptionalExpression(node, captureThisArg) { switch (node.kind) { case 199 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg); - case 193 /* PropertyAccessExpression */: return visitNonOptionalPropertyAccessExpression(node, captureThisArg); - case 194 /* ElementAccessExpression */: return visitNonOptionalElementAccessExpression(node, captureThisArg); + case 193 /* PropertyAccessExpression */: + case 194 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg); case 195 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } @@ -77473,31 +77953,36 @@ var ts; function visitOptionalExpression(node, captureThisArg) { var _a = flattenChain(node), expression = _a.expression, chain = _a.chain; var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0])); - var temp = ts.createTempVariable(hoistVariableDeclaration); var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined; var leftExpression = ts.isSyntheticReference(left) ? left.expression : left; - var rightExpression = temp; + var capturedLeft = leftExpression; + if (shouldCaptureInTempVariable(leftExpression)) { + capturedLeft = ts.createTempVariable(hoistVariableDeclaration); + leftExpression = ts.createAssignment(capturedLeft, leftExpression); + } + var rightExpression = capturedLeft; var thisArg; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { case 193 /* PropertyAccessExpression */: - if (i === chain.length - 1 && captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - rightExpression = ts.createParen(ts.createAssignment(thisArg, rightExpression)); - } - rightExpression = ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)); - break; case 194 /* ElementAccessExpression */: if (i === chain.length - 1 && captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - rightExpression = ts.createParen(ts.createAssignment(thisArg, rightExpression)); + if (shouldCaptureInTempVariable(rightExpression)) { + thisArg = ts.createTempVariable(hoistVariableDeclaration); + rightExpression = ts.createAssignment(thisArg, rightExpression); + } + else { + thisArg = rightExpression; + } } - rightExpression = ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); + rightExpression = segment.kind === 193 /* PropertyAccessExpression */ + ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) + : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; case 195 /* CallExpression */: if (i === 0 && leftThisArg) { - rightExpression = ts.createFunctionCall(rightExpression, leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); + rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 101 /* SuperKeyword */ ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } else { rightExpression = ts.createCall(rightExpression, @@ -77507,22 +77992,27 @@ var ts; } ts.setOriginalNode(rightExpression, segment); } - var target = ts.createConditional(ts.createLogicalOr(ts.createStrictEquality(ts.createAssignment(temp, leftExpression), ts.createNull()), ts.createStrictEquality(temp, ts.createVoidZero())), ts.createVoidZero(), rightExpression); + var target = ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createVoidZero(), rightExpression); return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target; } - function createNotNullCondition(node) { - return ts.createBinary(ts.createBinary(node, ts.createToken(37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(55 /* AmpersandAmpersandToken */), ts.createBinary(node, ts.createToken(37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero())); + function createNotNullCondition(left, right, invert) { + return ts.createBinary(ts.createBinary(left, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(invert ? 56 /* BarBarToken */ : 55 /* AmpersandAmpersandToken */), ts.createBinary(right, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero())); } function transformNullishCoalescingExpression(node) { - var expressions = []; var left = ts.visitNode(node.left, visitor, ts.isExpression); - if (!ts.isIdentifier(left)) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - expressions.push(ts.createAssignment(temp, left)); - left = temp; + var right = left; + if (shouldCaptureInTempVariable(left)) { + right = ts.createTempVariable(hoistVariableDeclaration); + left = ts.createAssignment(right, left); } - expressions.push(ts.createParen(ts.createConditional(createNotNullCondition(left), left, ts.visitNode(node.right, visitor, ts.isExpression)))); - return ts.inlineExpressions(expressions); + return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression)); + } + function shouldCaptureInTempVariable(expression) { + // don't capture identifiers and `this` in a temporary variable + // `super` cannot be captured as it's no real variable + return !ts.isIdentifier(expression) && + expression.kind !== 103 /* ThisKeyword */ && + expression.kind !== 101 /* SuperKeyword */; } } ts.transformESNext = transformESNext; @@ -87680,6 +88170,7 @@ var ts; var combinedStatements; if (ts.isSourceFileJS(currentSourceFile)) { combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); } else { @@ -89451,7 +89942,11 @@ var ts; bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) + return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) + emitSkipped = true; return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -92205,8 +92700,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_20 = types; _d < types_20.length; _d++) { - var directive = types_20[_d]; + for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { + var directive = types_21[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -94081,31 +94576,39 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (system.directoryExists(directoryPath)) { + if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } return false; } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - if (compilerHost.createDirectory) { - compilerHost.createDirectory(directoryPath); - } - else { - system.createDirectory(directoryPath); + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + // NOTE: If patchWriteFileEnsuringDirectory has been called, + // the system.writeFile will do its own directory creation and + // the ensureDirectoriesExist call will always be redundant. + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); } } } var outputFingerprints; - function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + function writeFileWorker(fileName, data, writeByteOrderMark) { + if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) { + system.writeFile(fileName, data, writeByteOrderMark); + return; + } if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = system.createHash(data); // TODO: GH#18217 - var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); + var mtimeBefore = system.getModifiedTime(fileName); if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -94117,32 +94620,13 @@ var ts; } } system.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, mtime: mtimeAfter }); } - function writeFile(fileName, data, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { - writeFileIfUpdated(fileName, data, writeByteOrderMark); - } - else { - system.writeFile(fileName, data, writeByteOrderMark); - } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -95864,9 +96348,16 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - if (fail) - fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + var canonicalFileName_1 = host.getCanonicalFileName(fileName); + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) { + if (fail) { + if (ts.hasJSFileExtension(canonicalFileName_1)) { + fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName); + } + else { + fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + } + } return undefined; } var sourceFile = getSourceFile(fileName); @@ -95880,7 +96371,7 @@ var ts; fail(ts.Diagnostics.File_0_not_found, fileName); } } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) { fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); } } @@ -95938,6 +96429,19 @@ var ts; function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) { if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(fileName); + // If preserveSymlinks is true, module resolution wont jump the symlink + // but the resolved real path may be the .d.ts from project reference + // Note:: Currently we try the real path only if the + // file is from node_modules to avoid having to run real path on all file paths + if (!source && + host.realpath && + options.preserveSymlinks && + ts.isDeclarationFileName(fileName) && + ts.stringContains(fileName, ts.nodeModulesPathPart)) { + var realPath = host.realpath(fileName); + if (realPath !== fileName) + source = getSourceOfProjectReferenceRedirect(realPath); + } if (source) { var file_1 = ts.isString(source) ? findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) : @@ -96468,9 +96972,6 @@ var ts; else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && ts.isIncrementalCompilation(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { @@ -97515,6 +98016,7 @@ var ts; ts.Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = ts.createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -98245,7 +98747,7 @@ var ts; } var state = { fileInfos: fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), @@ -98281,33 +98783,6 @@ var ts; } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; - function convertFromReusableCompilerOptions(options, toAbsolutePath) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - function convertFromReusableCompilerOptionValue(option, value, toAbsolutePath) { - if (option) { - if (option.type === "list") { - var values = value; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value); - } - } - return value; - } function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -99040,7 +99515,7 @@ var ts; function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { return { relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, - ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? + ending: ts.hasJSFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, }; @@ -99126,7 +99601,7 @@ var ts; var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } function numberOfDirectorySeparators(str) { @@ -99260,10 +99735,13 @@ var ts; // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); + var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { return undefined; + } // If the module was found in @types, get the actual Node package name var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); @@ -99488,7 +99966,7 @@ var ts; /** Parses config file using System interface */ function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; @@ -99512,7 +99990,7 @@ var ts; } ts.getErrorSummaryText = getErrorSummaryText; function listFiles(program, writeFileName) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { ts.forEach(program.getSourceFiles(), function (file) { writeFileName(file.fileName); }); @@ -99523,6 +100001,7 @@ var ts; * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -99531,13 +100010,17 @@ var ts; // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + if (!isListFilesOnly) { + ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + } } } // Emit and report any errors we ran into. - var emitResult = program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + var emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: ts.emptyArray } + : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics; ts.addRange(diagnostics, emitDiagnostics); ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); @@ -99640,19 +100123,13 @@ var ts; createHash: ts.maybeBind(host, host.createHash), readDirectory: ts.maybeBind(host, host.readDirectory), }; - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - if (host.createDirectory) - host.createDirectory(directoryPath); - } - } function writeFile(fileName, text, writeByteOrderMark, onError) { try { ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); + // NOTE: If patchWriteFileEnsuringDirectory has been called, + // the host.writeFile will do its own directory creation and + // the ensureDirectoriesExist call will always be redundant. + ts.writeFileEnsuringDirectories(fileName, text, writeByteOrderMark, function (path, data, writeByteOrderMark) { return host.writeFile(path, data, writeByteOrderMark); }, function (path) { return host.createDirectory(path); }, function (path) { return host.directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -101429,30 +101906,25 @@ var ts; setupInitialBuild(state, cancellationToken); var reportQueue = true; var successfulProjects = 0; - var errorProjects = 0; while (true) { var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; - } } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ts.ExitStatus.DiagnosticsPresent_OutputsGenerated : - ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : - ts.ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); }) + ? ts.ExitStatus.Success + : successfulProjects + ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated + : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); @@ -101460,7 +101932,7 @@ var ts; return ts.ExitStatus.InvalidProject_OutputsSkipped; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped; } var options = state.options, host = state.host; var filesToDelete = options.dry ? [] : undefined; @@ -103755,6 +104227,25 @@ var ts; return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); } ts.documentSpansEqual = documentSpansEqual; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + ts.forEachUnique = forEachUnique; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -104502,10 +104993,11 @@ var ts; } var dependencyKeys = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]; var stringContent = host.readFile(fileName); - var content = stringContent && tryParseJson(stringContent); - if (!content) { + if (!stringContent) return undefined; - } + var content = tryParseJson(stringContent); + if (!content) + return false; var info = {}; for (var _i = 0, dependencyKeys_1 = dependencyKeys; _i < dependencyKeys_1.length; _i++) { var key = dependencyKeys_1[_i]; @@ -105030,8 +105522,10 @@ var ts; }); return { spans: spans, endOfLineState: 0 /* None */ }; function pushClassification(start, end, type) { + var length = end - start; + ts.Debug.assert(length > 0, "Classification had non-positive length of " + length); spans.push(start); - spans.push(end - start); + spans.push(length); spans.push(type); } } @@ -105450,8 +105944,7 @@ var ts; return 25 /* bigintLiteral */; } else if (tokenKind === 10 /* StringLiteral */) { - // TODO: GH#18217 - return token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token && token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -105709,7 +106202,7 @@ var ts; var candidates = []; checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); var types = ts.flatMap(candidates, function (candidate) { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); @@ -106859,6 +107352,7 @@ var ts; var completionKind = 5 /* None */; var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; + // This also gets mutated in nested-functions after the return var symbols = []; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; @@ -106965,8 +107459,15 @@ var ts; var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -106983,8 +107484,15 @@ var ts; var type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -107286,7 +107794,7 @@ var ts; typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); } /** - * Gathers symbols that can be imported from other files, deduplicating along the way. Symbols can be “duplicates” + * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, * if and only if the the first can be imported (it may be excluded due to package.json filtering in @@ -107362,7 +107870,7 @@ var ts; // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -107476,7 +107984,16 @@ var ts; } if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) { if (contextToken.parent.kind === 266 /* JsxOpeningElement */) { - return true; + // Two possibilities: + // 1.
/**/ + // - contextToken: GreaterThanToken (before cursor) + // - location: JSXElement + // - different parents (JSXOpeningElement, JSXElement) + // 2. /**/> + // - contextToken: GreaterThanToken (before cursor) + // - location: GreaterThanToken (after cursor) + // - same parent (JSXOpeningElement) + return location.parent.kind !== 266 /* JsxOpeningElement */; } if (contextToken.parent.kind === 267 /* JsxClosingElement */ || contextToken.parent.kind === 265 /* JsxSelfClosingElement */) { return !!contextToken.parent.parent && contextToken.parent.parent.kind === 264 /* JsxElement */; @@ -107551,7 +108068,7 @@ var ts; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 192 /* ObjectLiteralExpression */) { - var typeForObject = typeChecker.getContextualType(objectLikeContainer); + var typeForObject = typeChecker.getContextualType(objectLikeContainer, 4 /* Completion */); if (!typeForObject) return 2 /* Fail */; isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); @@ -108128,6 +108645,8 @@ var ts; return isFunctionLikeBodyKeyword(kind) || kind === 129 /* DeclareKeyword */ || kind === 134 /* ModuleKeyword */ + || kind === 144 /* TypeKeyword */ + || kind === 135 /* NamespaceKeyword */ || ts.isTypeKeyword(kind) && kind !== 145 /* UndefinedKeyword */; case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); @@ -109937,7 +110456,7 @@ var ts; return undefined; } function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet) { - var moduleSourceFile = symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; + var moduleSourceFile = (symbol.flags & 1536 /* Module */) && symbol.declarations && ts.find(symbol.declarations, ts.isSourceFile); if (!moduleSourceFile) return undefined; var exportEquals = symbol.exports.get("export=" /* ExportEquals */); @@ -110662,8 +111181,10 @@ var ts; || exportSpecifier.name.originalKeywordKind === 83 /* DefaultKeyword */; var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); - var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); - searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + var exportInfo = FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker); + if (exportInfo) { + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { @@ -111874,7 +112395,7 @@ var ts; // The property length will have two declarations of property length coming // from Array - Array and Array var documentationComment = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var comment = _a[_i].comment; if (comment === undefined) @@ -111903,7 +112424,7 @@ var ts; function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); @@ -111940,24 +112461,6 @@ var ts; return comment === undefined ? s : s + " " + comment; } } - /** - * Iterates through 'array' by index and performs the callback on each element of array until the callback - * returns a truthy value, then returns that value. - * If no such value is found, the callback is applied to each element of array and undefined is returned. - */ - function forEachUnique(array, callback) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array.indexOf(array[i]) === i) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - } - } - return undefined; - } function getJSDocTagNameCompletions() { return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { @@ -112882,7 +113385,8 @@ var ts; } var declName = ts.getNameOfDeclaration(node); if (declName && ts.isPropertyName(declName)) { - return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 + var propertyName = ts.getPropertyNameForPropertyNameNode(declName); + return propertyName && ts.unescapeLeadingUnderscores(propertyName); } switch (node.kind) { case 200 /* FunctionExpression */: @@ -113652,6 +114156,9 @@ var ts; case 265 /* JsxSelfClosingElement */: case 266 /* JsxOpeningElement */: return spanForJSXAttributes(n.attributes); + case 210 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + return spanForTemplateLiteral(n); } function spanForJSXElement(node) { var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); @@ -113670,6 +114177,12 @@ var ts; } return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } + function spanForTemplateLiteral(node) { + if (node.kind === 14 /* NoSubstitutionTemplateLiteral */ && node.text.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); + } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 18 /* OpenBraceToken */; } // If the block has no leading keywords and is inside an array literal or call expression, @@ -115972,7 +116485,7 @@ var ts; // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration - var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + var locationIsSymbolDeclaration = symbol.declarations && ts.find(symbol.declarations, function (declaration) { return declaration === (location.kind === 128 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { @@ -116879,8 +117392,8 @@ var ts; rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */), // in other cases there should be no space between '?' and next token rule("NoSpaceAfterQuestionMark", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceBeforeDot", anyToken, [24 /* DotToken */, 28 /* QuestionDotToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceAfterDot", [24 /* DotToken */, 28 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBetweenImportParenInImportType", 95 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between @@ -119012,7 +119525,10 @@ var ts; if (ts.isCallOrNewExpression(parent)) { if (!parent.arguments) return false; - var currentNode = ts.Debug.assertDefined(ts.find(parent.arguments, function (arg) { return arg.pos === child.pos; })); + var currentNode = ts.find(parent.arguments, function (arg) { return arg.pos === child.pos; }); + // If it's not one of the arguments, don't look past this + if (!currentNode) + return false; var currentIndex = parent.arguments.indexOf(currentNode); if (currentIndex === 0) return false; // Can't look at previous node if first @@ -119431,6 +119947,18 @@ var ts; cb(tracker); return tracker.getChanges(); }; + ChangeTracker.prototype.pushRaw = function (sourceFile, change) { + ts.Debug.assertEqual(sourceFile.fileName, change.fileName); + for (var _i = 0, _a = change.textChanges; _i < _a.length; _i++) { + var c = _a[_i]; + this.changes.push({ + kind: ChangeKind.Text, + sourceFile: sourceFile, + text: c.newText, + range: ts.createTextRangeFromSpan(c.span), + }); + } + }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); }; @@ -119559,7 +120087,7 @@ var ts; endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); if (!endNode) { if (!ts.isArrowFunction(node)) - return; // Function missing parentheses, give up + return false; // Function missing parentheses, give up // If no `)`, is an arrow function `x => x`, so use the end of the first parameter endNode = ts.first(node.parameters); } @@ -119568,6 +120096,7 @@ var ts; endNode = node.kind !== 241 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + return true; }; ChangeTracker.prototype.tryInsertThisTypeAnnotation = function (sourceFile, node, type) { var start = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1; @@ -121194,20 +121723,20 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, formatContext, preferences); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, formatContext, preferences); }); }, }); @@ -121247,7 +121776,7 @@ var ts; } return errorCode; } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, formatContext, preferences) { if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 103 /* ThisKeyword */) { return undefined; } @@ -121258,7 +121787,7 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken, formatContext, preferences); return parent; } if (ts.isPropertyAccessExpression(parent)) { @@ -121275,7 +121804,7 @@ var ts; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken, formatContext, preferences); return symbol.valueDeclaration; } return undefined; @@ -121289,14 +121818,14 @@ var ts; // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken, formatContext, preferences); return param; } return undefined; @@ -121304,14 +121833,14 @@ var ts; case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host, formatContext, preferences); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } return undefined; @@ -121326,12 +121855,12 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken, formatContext, preferences) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host, formatContext, preferences); } } - function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken, formatContext, preferences) { if (!ts.isIdentifier(parameterDeclaration.name)) { return; } @@ -121347,7 +121876,7 @@ var ts; for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; if (declaration && !declaration.type && !declaration.initializer) { - annotate(changes, sourceFile, declaration, type, program, host); + annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences); } } if (needParens) @@ -121376,7 +121905,7 @@ var ts; ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)), ]); } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken, formatContext, preferences) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); @@ -121387,11 +121916,11 @@ var ts; annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); } else { - annotate(changes, sourceFile, param, type, program, host); + annotate(changes, sourceFile, param, type, program, host, formatContext, preferences); } } } - function annotate(changes, sourceFile, declaration, type, program, host) { + function annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (ts.isInJSFile(sourceFile) && declaration.kind !== 157 /* PropertySignature */) { @@ -121403,11 +121932,32 @@ var ts; var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); addJSDocTags(changes, sourceFile, parent, [typeTag]); } - else { + else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences)) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } } } + function tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences) { + var _a; + if (ts.isLiteralImportTypeNode(typeNode) && typeNode.qualifier && type.symbol) { + // Replace 'import("./a").SomeType' with 'SomeType' and an actual import if possible + var moduleSymbol = (_a = ts.find(type.symbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) === null || _a === void 0 ? void 0 : _a.getSourceFile().symbol; + // Symbol for the left-most thing after the dot + if (moduleSymbol) { + var symbol = ts.getFirstIdentifier(typeNode.qualifier).symbol; + var action = codefix.getImportCompletionAction(symbol, moduleSymbol, sourceFile, symbol.name, host, program, formatContext, declaration.pos, preferences); + if (action.codeAction.changes.length && changes.tryInsertTypeAnnotation(sourceFile, declaration, ts.createTypeReferenceNode(typeNode.qualifier, typeNode.typeArguments))) { + for (var _i = 0, _b = action.codeAction.changes; _i < _b.length; _i++) { + var change = _b[_i]; + var file = sourceFile.fileName === change.fileName ? sourceFile : ts.Debug.assertDefined(program.getSourceFile(change.fileName)); + changes.pushRaw(file, change); + } + return true; + } + } + } + return false; + } function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { var signature = parameterInferences.length && parameterInferences[0].declaration.parent; if (!signature) { @@ -122099,7 +122649,7 @@ var ts; } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); } function addCandidateType(usage, type) { if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { @@ -123906,6 +124456,7 @@ var ts; var filteredCount = 0; var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host); var allSourceFiles = program.getSourceFiles(); + var globalTypingsCache = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); forEachExternalModule(program.getTypeChecker(), allSourceFiles, function (module, sourceFile) { if (sourceFile === undefined) { if (!packageJson || packageJson.allowsImportingAmbientModule(module, allSourceFiles)) { @@ -123915,7 +124466,9 @@ var ts; filteredCount++; } } - else if (sourceFile && sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + else if (sourceFile && + sourceFile !== from && + isImportablePath(from.fileName, sourceFile.fileName, ts.hostGetCanonicalFileName(host), globalTypingsCache)) { if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile, allSourceFiles)) { cb(module); } @@ -123945,10 +124498,13 @@ var ts; * Don't include something from a `node_modules` that isn't actually reachable by a global import. * A relative import to node_modules is usually a bad idea. */ - function isImportablePath(fromPath, toPath) { + function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } function moduleSymbolToValidIdentifier(moduleSymbol, target) { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); @@ -123993,6 +124549,7 @@ var ts; readFile: ts.maybeBind(host, host.readFile), useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || program.getProbableSymlinks, + getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), }; var usesNodeCoreModules; return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; @@ -125568,14 +126125,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); - if (sig.hasRestParameter) { + if (ts.signatureHasRestParameter(sig)) { someSigHasRestParameter = true; } - if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!ts.signatureHasRestParameter(sig) || ts.signatureHasRestParameter(maxArgsSignature))) { maxArgsSignature = sig; } } - var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + var maxNonRestArgs = maxArgsSignature.parameters.length - (ts.signatureHasRestParameter(maxArgsSignature) ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { @@ -128060,7 +128617,7 @@ var ts; if (!selection || !ts.isTypeNode(selection)) return undefined; var checker = context.program.getTypeChecker(); - var firstStatement = ts.Debug.assertDefined(isJS ? ts.findAncestor(selection, isStatementAndHasJSDoc) : ts.findAncestor(selection, ts.isStatement), "Should find a statement"); + var firstStatement = ts.Debug.assertDefined(ts.findAncestor(selection, ts.isStatement), "Should find a statement"); var typeParameters = collectTypeParameters(checker, selection, firstStatement, file); if (!typeParameters) return undefined; @@ -128091,9 +128648,6 @@ var ts; } return undefined; } - function isStatementAndHasJSDoc(n) { - return ts.isStatement(n) && ts.hasJSDocNodes(n); - } function rangeContainsSkipTrivia(r1, node, file) { return ts.rangeContainsStartEnd(r1, ts.skipTrivia(file.text, node.pos), node.end); } @@ -130017,8 +130571,9 @@ var ts; return TypeObject; }()); var SignatureObject = /** @class */ (function () { - function SignatureObject(checker) { + function SignatureObject(checker, flags) { this.checker = checker; + this.flags = flags; } SignatureObject.prototype.getDeclaration = function () { return this.declaration; @@ -130056,13 +130611,12 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + ts.forEachUnique(declarations, function (declaration) { var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); - } + }); } return doc; } @@ -130373,9 +130927,7 @@ var ts; names.push(entry); } else { - if (entry.scriptKind !== 6 /* JSON */) { - names.push(entry.hostFileName); - } + names.push(entry.hostFileName); } }); return names; @@ -130943,12 +131495,11 @@ var ts; var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName, emitOnlyDtsFiles) { - if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + return ts.getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit); } // Signature help /** @@ -133734,16 +134285,31 @@ var ts; case 1: return this.containingProjects[0]; default: - // if this file belongs to multiple projects, the first configured project should be - // the default project; if no configured projects, the first external project should - // be the default project; otherwise the first inferred project should be the default. + // If this file belongs to multiple projects, below is the order in which default project is used + // - for open script info, its default configured project during opening is default if info is part of it + // - first configured project of which script info is not a source of project reference redirect + // - first configured project + // - first external project + // - first inferred project var firstExternalProject = void 0; var firstConfiguredProject = void 0; - for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { - var project = _a[_i]; + var firstNonSourceOfProjectReferenceRedirect = void 0; + var defaultConfiguredProject = void 0; + for (var index = 0; index < this.containingProjects.length; index++) { + var project = this.containingProjects[index]; if (project.projectKind === server.ProjectKind.Configured) { - if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) - return project; + if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) { + // If we havent found default configuredProject and + // its not the last one, find it and use that one if there + if (defaultConfiguredProject === undefined && + index !== this.containingProjects.length - 1) { + defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false; + } + if (defaultConfiguredProject === project) + return project; + if (!firstNonSourceOfProjectReferenceRedirect) + firstNonSourceOfProjectReferenceRedirect = project; + } if (!firstConfiguredProject) firstConfiguredProject = project; } @@ -133751,7 +134317,11 @@ var ts; firstExternalProject = project; } } - return firstConfiguredProject || firstExternalProject || this.containingProjects[0]; + return defaultConfiguredProject || + firstNonSourceOfProjectReferenceRedirect || + firstConfiguredProject || + firstExternalProject || + this.containingProjects[0]; } }; ScriptInfo.prototype.registerFileUpdate = function () { @@ -134050,7 +134620,7 @@ var ts; var Project = /** @class */ (function () { /*@internal*/ function Project( - /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { + /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory, customRealpath) { var _this = this; this.projectName = projectName; this.projectKind = projectKind; @@ -134120,7 +134690,7 @@ var ts; this.trace = function (s) { return host.trace(s); }; } if (host.realpath) { - this.realpath = function (path) { return host.realpath(path); }; + this.realpath = customRealpath || (function (path) { return host.realpath(path); }); } // Use the current directory as resolution root only if the project created using current directory string this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, /*logChangesWhenResolvingModule*/ true); @@ -134161,6 +134731,10 @@ var ts; Project.prototype.installPackage = function (options) { return this.typingsCache.installPackage(__assign(__assign({}, options), { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); }; + /*@internal*/ + Project.prototype.getGlobalTypingsCacheLocation = function () { + return this.getGlobalCache(); + }; Object.defineProperty(Project.prototype, "typingsCache", { get: function () { return this.projectService.typingsCache; @@ -135060,9 +135634,11 @@ var ts; this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } - // Search our peer node_modules, then any globally-specified probe paths - // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ - var searchPaths = __spreadArrays([ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")], this.projectService.pluginProbeLocations); + // Search any globally-specified probe paths, then our peer node_modules + var searchPaths = __spreadArrays(this.projectService.pluginProbeLocations, [ + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ + ts.combinePaths(this.projectService.getExecutingFilePath(), "../../.."), + ]); if (this.projectService.globalPlugins) { var _loop_2 = function (globalPluginName) { // Skip empty names from odd commandline parses @@ -135168,7 +135744,9 @@ var ts; case -1 /* True */: var packageJsonFileName = ts.combinePaths(directory, "package.json"); watchPackageJsonFile(packageJsonFileName); - result.push(ts.Debug.assertDefined(packageJsonCache.getInDirectory(directory))); + var info = packageJsonCache.getInDirectory(directory); + if (info) + result.push(info); } if (rootPath && rootPath === toPath(directory)) { return true; @@ -135336,7 +135914,7 @@ var ts; /*hasExplicitListOfFiles*/ false, /*lastFileExceededProgramSize*/ undefined, /*compilerOptions*/ {}, - /*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; + /*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName), projectService.host.realpath && (function (s) { return _this.getRealpath(s); })) || this; /*@internal*/ _this.canConfigFileJsonReportNoInputFiles = false; /** Ref count to the project when opened from external project */ @@ -135354,19 +135932,31 @@ var ts; ConfiguredProject.prototype.setResolvedProjectReferenceCallbacks = function (projectReferenceCallbacks) { this.projectReferenceCallbacks = projectReferenceCallbacks; }; + ConfiguredProject.prototype.fileExistsIfProjectReferenceDts = function (file) { + var source = this.projectReferenceCallbacks.getSourceOfProjectReferenceRedirect(file); + return source !== undefined ? + ts.isString(source) ? _super.prototype.fileExists.call(this, source) : true : + undefined; + }; /** * This implementation of fileExists checks if the file being requested is * .d.ts file for the referenced Project. * If it is it returns true irrespective of whether that file exists on host */ ConfiguredProject.prototype.fileExists = function (file) { + if (_super.prototype.fileExists.call(this, file)) + return true; + if (!this.useSourceOfProjectReferenceRedirect() || !this.projectReferenceCallbacks) + return false; + if (!ts.isDeclarationFileName(file)) + return false; // Project references go to source file instead of .d.ts file - if (this.useSourceOfProjectReferenceRedirect() && this.projectReferenceCallbacks) { - var source = this.projectReferenceCallbacks.getSourceOfProjectReferenceRedirect(file); - if (source) - return ts.isString(source) ? _super.prototype.fileExists.call(this, source) : true; - } - return _super.prototype.fileExists.call(this, file); + return this.fileOrDirectoryExistsUsingSource(file, /*isFile*/ true); + }; + ConfiguredProject.prototype.directoryExistsIfProjectReferenceDeclDir = function (dir) { + var dirPath = this.toPath(dir); + var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator; + return ts.forEachKey(this.mapOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath || ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator); }); }; /** * This implementation of directoryExists checks if the directory being requested is @@ -135375,8 +135965,10 @@ var ts; */ ConfiguredProject.prototype.directoryExists = function (path) { var _this = this; - if (_super.prototype.directoryExists.call(this, path)) + if (_super.prototype.directoryExists.call(this, path)) { + this.handleDirectoryCouldBeSymlink(path); return true; + } if (!this.useSourceOfProjectReferenceRedirect() || !this.projectReferenceCallbacks) return false; if (!this.mapOfDeclarationDirectories) { @@ -135384,7 +135976,7 @@ var ts; this.projectReferenceCallbacks.forEachResolvedProjectReference(function (ref) { if (!ref) return; - var out = ref.commandLine.options.outFile || ref.commandLine.options.outDir; + var out = ref.commandLine.options.outFile || ref.commandLine.options.out; if (out) { _this.mapOfDeclarationDirectories.set(ts.getDirectoryPath(_this.toPath(out)), true); } @@ -135397,9 +135989,70 @@ var ts; } }); } - var dirPath = this.toPath(path); - var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator; - return !!ts.forEachKey(this.mapOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath || ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator); }); + return this.fileOrDirectoryExistsUsingSource(path, /*isFile*/ false); + }; + ConfiguredProject.prototype.realpathIfSymlinkedProjectReferenceDts = function (s) { + return this.symlinkedFiles && this.symlinkedFiles.get(this.toPath(s)); + }; + ConfiguredProject.prototype.getRealpath = function (s) { + return this.realpathIfSymlinkedProjectReferenceDts(s) || + this.projectService.host.realpath(s); + }; + ConfiguredProject.prototype.handleDirectoryCouldBeSymlink = function (directory) { + if (!this.useSourceOfProjectReferenceRedirect() || !this.projectReferenceCallbacks) + return; + // Because we already watch node_modules, handle symlinks in there + if (!this.realpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) + return; + if (!this.symlinkedDirectories) + this.symlinkedDirectories = ts.createMap(); + var directoryPath = ts.ensureTrailingDirectorySeparator(this.toPath(directory)); + if (this.symlinkedDirectories.has(directoryPath)) + return; + var real = this.projectService.host.realpath(directory); + var realPath; + if (real === directory || + (realPath = ts.ensureTrailingDirectorySeparator(this.toPath(real))) === directoryPath) { + // not symlinked + this.symlinkedDirectories.set(directoryPath, false); + return; + } + this.symlinkedDirectories.set(directoryPath, { + real: ts.ensureTrailingDirectorySeparator(real), + realPath: realPath + }); + }; + ConfiguredProject.prototype.fileOrDirectoryExistsUsingSource = function (fileOrDirectory, isFile) { + var _this = this; + var fileOrDirectoryExistsUsingSource = isFile ? + function (file) { return _this.fileExistsIfProjectReferenceDts(file); } : + function (dir) { return _this.directoryExistsIfProjectReferenceDeclDir(dir); }; + // Check current directory or file + var result = fileOrDirectoryExistsUsingSource(fileOrDirectory); + if (result !== undefined) + return result; + if (!this.symlinkedDirectories) + return false; + var fileOrDirectoryPath = this.toPath(fileOrDirectory); + if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart)) + return false; + if (isFile && this.symlinkedFiles && this.symlinkedFiles.has(fileOrDirectoryPath)) + return true; + // If it contains node_modules check if its one of the symlinked path we know of + return ts.firstDefinedIterator(this.symlinkedDirectories.entries(), function (_a) { + var directoryPath = _a[0], symlinkedDirectory = _a[1]; + if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath)) + return undefined; + var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath)); + if (isFile && result) { + if (!_this.symlinkedFiles) + _this.symlinkedFiles = ts.createMap(); + // Store the real path for the file' + var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, _this.currentDirectory); + _this.symlinkedFiles.set(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), "")); + } + return result; + }) || false; }; /** * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph @@ -135411,6 +136064,8 @@ var ts; this.pendingReload = ts.ConfigFileProgramReloadLevel.None; this.projectReferenceCallbacks = undefined; this.mapOfDeclarationDirectories = undefined; + this.symlinkedDirectories = undefined; + this.symlinkedFiles = undefined; var result; switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: @@ -135521,6 +136176,8 @@ var ts; this.configFileSpecs = undefined; this.projectReferenceCallbacks = undefined; this.mapOfDeclarationDirectories = undefined; + this.symlinkedDirectories = undefined; + this.symlinkedFiles = undefined; _super.prototype.close.call(this); }; /* @internal */ @@ -136377,7 +137034,7 @@ var ts; ts.Debug.assert(info.isOrphan()); var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || this.getOrCreateSingleInferredProjectIfEnabled() || - this.getOrCreateSingleInferredWithoutProjectRoot(info.isDynamic ? this.currentDirectory : ts.getDirectoryPath(info.path)); + this.getOrCreateSingleInferredWithoutProjectRoot(info.isDynamic ? projectRootPath || this.currentDirectory : ts.getDirectoryPath(info.path)); project.addRoot(info); if (info.containingProjects[0] !== project) { // Ensure this is first project, we could be in this scenario because info could be part of orphan project @@ -136700,6 +137357,9 @@ var ts; } ts.Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path)); var projectRootPath = this.openFiles.get(info.path); + var scriptInfo = ts.Debug.assertDefined(this.getScriptInfo(info.path)); + if (scriptInfo.isDynamic) + return undefined; var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName)); var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); }; // If projectRootPath doesn't contain info.path, then do normal search for config file @@ -136724,6 +137384,14 @@ var ts; } while (anySearchPathOk || isSearchPathInProjectRoot()); return undefined; }; + /*@internal*/ + ProjectService.prototype.findDefaultConfiguredProject = function (info) { + if (!info.isScriptOpen()) + return undefined; + var configFileName = this.getConfigFileNameForFile(info); + return configFileName && + this.findConfiguredProjectByProjectName(configFileName); + }; /** * This function tries to search for a tsconfig.json for the given file. * This is different from the method the compiler uses because @@ -137063,7 +137731,9 @@ var ts; }); }; ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) { - if (info.isDynamic || !this.useInferredProjectPerProjectRoot) { + if (!this.useInferredProjectPerProjectRoot || + // Its a dynamic info opened without project root + (info.isDynamic && projectRootPath === undefined)) { return undefined; } if (projectRootPath) { @@ -137322,7 +137992,7 @@ var ts; var isDynamic = server.isDynamicFileName(fileName); ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info or in context of host currentDirectory"; }); ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; }); - ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; }); + ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory || this.useInferredProjectPerProjectRoot, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always be opened with service's current directory or service should support inferred project per projectRootPath."; }); // If the file is not opened by client and the file doesnot exist on the disk, return if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { return; @@ -137333,7 +138003,7 @@ var ts; if (!openedByClient) { this.watchClosedScriptInfo(info); } - else if (!ts.isRootedDiskPath(fileName) && !isDynamic) { + else if (!ts.isRootedDiskPath(fileName) && (!isDynamic || this.currentDirectory !== currentDirectory)) { // File that is opened by user but isn't rooted disk path this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); } @@ -138324,7 +138994,7 @@ var ts; directoriesWithoutPackageJson.set(ts.getDirectoryPath(fileName), true); }, getInDirectory: function (directory) { - return packageJsons.get(ts.combinePaths(directory, "package.json")); + return packageJsons.get(ts.combinePaths(directory, "package.json")) || undefined; }, directoryHasPackageJson: directoryHasPackageJson, searchDirectoryAndAncestors: function (directory) { @@ -138344,7 +139014,7 @@ var ts; }; function addOrUpdate(fileName) { var packageJsonInfo = ts.createPackageJsonInfo(fileName, project); - if (packageJsonInfo) { + if (packageJsonInfo !== undefined) { packageJsons.set(fileName, packageJsonInfo); directoriesWithoutPackageJson.delete(ts.getDirectoryPath(fileName)); } diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 932199e6e36..433217ee422 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.7"; + const versionMajorMinor = "3.8"; /** The version of the TypeScript compiler release */ const version: string; } @@ -1964,6 +1964,8 @@ declare namespace ts { DiagnosticsPresent_OutputsSkipped = 1, DiagnosticsPresent_OutputsGenerated = 2, InvalidProject_OutputsSkipped = 3, + ProjectReferenceCycle_OutputsSkipped = 4, + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ProjectReferenceCycle_OutputsSkupped = 4 } export interface EmitResult { @@ -2376,6 +2378,7 @@ declare namespace ts { JSLiteral = 16384, FreshLiteral = 32768, ArrayLiteral = 65536, + ObjectRestType = 131072, ClassOrInterface = 3, } export interface ObjectType extends Type { @@ -3169,8 +3172,9 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + readonly importModuleSpecifierPreference?: "auto" | "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: boolean; @@ -3522,6 +3526,7 @@ declare namespace ts { function isCallExpression(node: Node): node is CallExpression; function isCallChain(node: Node): node is CallChain; function isOptionalChain(node: Node): node is PropertyAccessChain | ElementAccessChain | CallChain; + function isNullishCoalesce(node: Node): boolean; function isNewExpression(node: Node): node is NewExpression; function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression; function isTypeAssertion(node: Node): node is TypeAssertion; @@ -5071,7 +5076,7 @@ declare namespace ts { 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[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; dispose(): void; } @@ -5194,7 +5199,7 @@ declare namespace ts { } interface FileTextChanges { fileName: string; - textChanges: TextChange[]; + textChanges: readonly TextChange[]; isNewFile?: boolean; } interface CodeAction { diff --git a/lib/typescript.js b/lib/typescript.js index 8102884ad12..b1d5c0c5098 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -76,67 +76,20 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +/* @internal */ var ts; (function (ts) { - // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. - // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.7"; - /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; -})(ts || (ts = {})); -(function (ts) { - /* @internal */ - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - ts.emptyArray = []; - /** Create a MapLike with good performance. */ - function createDictionaryObject() { - var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - return map; - } - /** Create a new map. If a template object is provided, the map will copy entries from it. */ - function createMap() { - return new ts.MapCtr(); - } - ts.createMap = createMap; - function createMapFromEntries(entries) { - var map = createMap(); - for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { - var _a = entries_1[_i], key = _a[0], value = _a[1]; - map.set(key, value); + function createMapShim() { + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; } - return map; - } - ts.createMapFromEntries = createMapFromEntries; - function createMapFromTemplate(template) { - var map = new ts.MapCtr(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in template) { - if (hasOwnProperty.call(template, key)) { - map.set(key, template[key]); - } - } - return map; - } - ts.createMapFromTemplate = createMapFromTemplate; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // eslint-disable-next-line no-in-operator - ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - // Keep the class inside a function so it doesn't get compiled if it's not used. - function shimMap() { var MapIterator = /** @class */ (function () { function MapIterator(currentEntry, selector) { this.currentEntry = currentEntry; @@ -272,7 +225,75 @@ var ts; return class_1; }()); } - ts.shimMap = shimMap; + ts.createMapShim = createMapShim; +})(ts || (ts = {})); +var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.8"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".0-dev"; +})(ts || (ts = {})); +(function (ts) { + /* @internal */ + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + /** + * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). + */ + function tryGetNativeMap() { + // Internet Explorer's Map doesn't support iteration, so don't use it. + // eslint-disable-next-line no-in-operator + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; + } + ts.tryGetNativeMap = tryGetNativeMap; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + ts.Map = ts.tryGetNativeMap() || (function () { + // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it. + if (typeof ts.createMapShim === "function") { + return ts.createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); + /** Create a new map. */ + function createMap() { + return new ts.Map(); + } + ts.createMap = createMap; + /** Create a new map from an array of entries. */ + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + /** Create a new map from a template object is provided, the map will copy entries from it. */ + function createMapFromTemplate(template) { + var map = new ts.Map(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; function length(array) { return array ? array.length : 0; } @@ -1854,20 +1875,6 @@ var ts; return str.indexOf(substring) !== -1; } ts.stringContains = stringContains; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -2181,11 +2188,14 @@ var ts; if (isFlags) { var result = ""; var remainingFlags = value; - for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { - var _a = members[i], enumValue = _a[0], enumName = _a[1]; - if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; + if (enumValue > value) { + break; + } + if (enumValue !== 0 && enumValue & value) { + result = "" + result + (result ? "|" : "") + enumName; remainingFlags &= ~enumValue; - result = "" + enumName + (result ? "|" : "") + result; } } if (remainingFlags === 0) { @@ -2193,8 +2203,8 @@ var ts; } } else { - for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { - var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + for (var _b = 0, members_2 = members; _b < members_2.length; _b++) { + var _c = members_2[_b], enumValue = _c[0], enumName = _c[1]; if (enumValue === value) { return enumName; } @@ -2268,6 +2278,33 @@ var ts; ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; var isDebugInfoEnabled = false; + var extendedDebugModule; + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + Debug.formatControlFlowGraph = formatControlFlowGraph; + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator + Object.defineProperties(flowNode, { + __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } }, + __debugToString: { value: function () { return formatControlFlowGraph(this); } } + }); + } + } + } + Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; /** * Injects debug information into frequently used types. */ @@ -2311,6 +2348,20 @@ var ts; }); } } + // attempt to load extended debugging information + try { + if (ts.sys && ts.sys.require) { + var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath())); + var result = ts.sys.require(basePath, "./compiler-debug"); + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch (_a) { + // do nothing + } isDebugInfoEnabled = true; } Debug.enableDebugInfo = enableDebugInfo; @@ -2474,8 +2525,6 @@ var ts; } /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - var args = typeof process === "undefined" ? [] : process.argv; - ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(args)); })(ts || (ts = {})); /* @internal */ var ts; @@ -3370,6 +3419,7 @@ var ts; /* @internal */ TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + // NOTE: Ensure this is up-to-date with src/debug/debug.ts var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -3425,6 +3475,8 @@ var ts; // When build skipped because passed in project is invalid ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped"; // When build is skipped because project references form cycle + ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ @@ -3434,6 +3486,14 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + /* @internal */ + var ContextFlags; + (function (ContextFlags) { + ContextFlags[ContextFlags["None"] = 0] = "None"; + ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; + ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; + ContextFlags[ContextFlags["Completion"] = 4] = "Completion"; + })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {})); // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { @@ -3836,19 +3896,20 @@ var ts; ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 131072] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 262144] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 524288] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 1048576] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 786432] = "RequiresWidening"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 1835008] = "PropagatingFlags"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -3875,6 +3936,20 @@ var ts; SignatureKind[SignatureKind["Call"] = 0] = "Call"; SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + /* @internal */ + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter"; + SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes"; + SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain"; + SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain"; + // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us + // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when + // instantiating the return type. + SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags"; + SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags"; + })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {})); var IndexKind; (function (IndexKind) { IndexKind[IndexKind["String"] = 0] = "String"; @@ -4875,16 +4950,6 @@ var ts; } } ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; - function recursiveCreateDirectory(directoryPath, sys) { - var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); - if (shouldCreateParent) { - recursiveCreateDirectory(basePath, sys); - } - if (shouldCreateParent || !sys.directoryExists(directoryPath)) { - sys.createDirectory(directoryPath); - } - } /** * patch writefile to create folder before writing the file */ @@ -4893,11 +4958,7 @@ var ts; // patch writefile to create folder before writing the file var originalWriteFile = sys.writeFile; sys.writeFile = function (path, data, writeBom) { - var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); - if (directoryPath && !sys.directoryExists(directoryPath)) { - recursiveCreateDirectory(directoryPath, sys); - } - originalWriteFile.call(sys, path, data, writeBom); + return ts.writeFileEnsuringDirectories(path, data, !!writeBom, function (path, data, writeByteOrderMark) { return originalWriteFile.call(sys, path, data, writeByteOrderMark); }, function (path) { return sys.createDirectory(path); }, function (path) { return sys.directoryExists(path); }); }; } ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory; @@ -5046,6 +5107,15 @@ var ts; bufferFrom: bufferFrom, base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + require: function (baseDir, moduleName) { + try { + var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath: modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error: error }; + } + } }; return nodeSystem; /** @@ -5184,6 +5254,7 @@ var ts; if (fsSupportsRecursive) { return watchDirectoryUsingFsWatch; } + // defer watchDirectoryRecursively as it depends on `ts.createMap()` which may not be usable yet. var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? createWatchDirectoryUsing(fsWatchFile) : tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? @@ -5628,6 +5699,673 @@ var ts; ts.Debug.isDebugging = true; } })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + //// Path Tests + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + //// Path Parsing + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArrays([root], rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + //// Path Formatting + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + //// Path Normalization + /** + * Normalize path separators, converting `\` into `/`. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + //// Path Comparisons + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * @deprecated Use `containsPath` if possible. + */ + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + //// Relative Paths + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArrays([""], relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; +})(ts || (ts = {})); // // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ @@ -5655,7 +6393,7 @@ var ts; An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), - An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), @@ -5863,7 +6601,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd_1323", "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5899,6 +6637,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"), 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), @@ -6026,7 +6765,6 @@ var ts; Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), @@ -6196,8 +6934,8 @@ var ts; JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2610, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_proper_2610", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member property."), - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2611, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_access_2611", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member accessor."), + _0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property: diag(2610, ts.DiagnosticCategory.Error, "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610", "'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property."), + _0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor: diag(2611, ts.DiagnosticCategory.Error, "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611", "'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor."), Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), @@ -6420,6 +7158,8 @@ var ts; Parameter_0_of_accessor_has_or_is_using_private_name_1: diag(4106, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106", "Parameter '{0}' of accessor has or is using private name '{1}'."), Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2: diag(4107, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107", "Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'."), Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4108, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108", "Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named."), + Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), + Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -6427,6 +7167,7 @@ var ts; Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Unknown_compiler_option_0_Did_you_mean_1: diag(5025, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"), Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), @@ -6457,6 +7198,7 @@ var ts; 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}'?"), 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."), @@ -6503,7 +7245,7 @@ var ts; Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has an unsupported extension. The only supported extensions are {1}."), Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), @@ -6711,6 +7453,8 @@ var ts; 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."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), + File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -6814,6 +7558,7 @@ var ts; Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), + Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"), Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), @@ -9046,7 +9791,7 @@ var ts; ts.getDeclarationOfKind = getDeclarationOfKind; /** Create a new escaped identifier map. */ function createUnderscoreEscapedMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; function hasEntries(map) { @@ -9102,13 +9847,6 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -9915,6 +10653,11 @@ var ts; break; case 201 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); + case 275 /* CaseClause */: + case 276 /* DefaultClause */: + var start = ts.skipTrivia(sourceFile.text, node.pos); + var end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return ts.createTextSpanFromBounds(start, end); } if (errorNode === undefined) { // If we don't have a better node, then just set the error on the first token of @@ -10727,7 +11470,7 @@ var ts; (node.typeArguments[0].kind === 142 /* StringKeyword */ || node.typeArguments[0].kind === 139 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 195 /* CallExpression */) { return false; } @@ -10739,7 +11482,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -10961,27 +11704,31 @@ var ts; isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true); } ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; - function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { - return isLiteralLikeElementAccess(node) - && ((!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */) || - isEntityNameExpression(node.expression) || - isBindableStaticElementAccessExpression(node.expression, /*excludeThisKeyword*/ true)); - } - ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression; + /** x.y OR x[0] */ function isLiteralLikeAccess(node) { return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node); } ts.isLiteralLikeAccess = isLiteralLikeAccess; + /** x[0] OR x['a'] OR x[Symbol.y] */ function isLiteralLikeElementAccess(node) { return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) || isWellKnownSymbolSyntactically(node.argumentExpression)); } ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; + /** Any series of property and element accesses. */ function isBindableStaticAccessExpression(node, excludeThisKeyword) { return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */ || isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; + /** Any series of property and element accesses, ending in a literal element access */ + function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { + return isLiteralLikeElementAccess(node) + && ((!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */) || + isEntityNameExpression(node.expression) || + isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true)); + } + ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression; function isBindableStaticNameExpression(node, excludeThisKeyword) { return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword); } @@ -11010,7 +11757,7 @@ var ts; if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) { return 0 /* None */; } - if (isBindableStaticNameExpression(expr.left.expression) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { // F.prototype = { ... } return 6 /* Prototype */; } @@ -11066,13 +11813,17 @@ var ts; nextToLast = nextToLast.expression; } var id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { - // exports.name = expr OR module.exports.name = expr + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + // ExportsProperty does not support binding with computed names + isBindableStaticAccessExpression(lhs)) { + // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return 1 /* ExportsProperty */; } - // F.G...x = expr - return 5 /* Property */; + if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs) && lhs.expression.kind !== 103 /* ThisKeyword */)) { + // F.G...x = expr + return 5 /* Property */; + } } return 0 /* None */; } @@ -12394,7 +13145,7 @@ var ts; */ function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); var extensionless = ts.removeFileExtension(relativePath); @@ -12477,6 +13228,25 @@ var ts; }, sourceFiles); } ts.writeFile = writeFile; + function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists); + createDirectory(directoryPath); + } + } + function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) { + // PERF: Checking for directory existence is expensive. Instead, assume the directory exists + // and fall back to creating it if the file write fails. + try { + writeFile(path, data, writeByteOrderMark); + } + catch (_a) { + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists); + writeFile(path, data, writeByteOrderMark); + } + } + ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories; function getLineOfLocalPosition(currentSourceFile, pos) { return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; } @@ -12916,6 +13686,23 @@ var ts; return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function getFirstIdentifier(node) { + switch (node.kind) { + case 75 /* Identifier */: + return node; + case 152 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 75 /* Identifier */); + return node; + case 193 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 75 /* Identifier */); + return node; + } + } + ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { return node.kind === 75 /* Identifier */ || node.kind === 103 /* ThisKeyword */ || node.kind === 193 /* PropertyAccessExpression */ && isDottedName(node.expression) || @@ -13434,20 +14221,6 @@ var ts; }); } ts.mutateMap = mutateMap; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); @@ -13474,7 +14247,7 @@ var ts; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { @@ -14539,11 +15312,47 @@ var ts; } ts.isCallChain = isCallChain; function isOptionalChain(node) { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + var kind = node.kind; + return !!(node.flags & 32 /* OptionalChain */) && + (kind === 193 /* PropertyAccessExpression */ + || kind === 194 /* ElementAccessExpression */ + || kind === 195 /* CallExpression */); } ts.isOptionalChain = isOptionalChain; + /* @internal */ + function isOptionalChainRoot(node) { + return isOptionalChain(node) && !!node.questionDotToken; + } + ts.isOptionalChainRoot = isOptionalChainRoot; + /** + * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`). + */ + /* @internal */ + function isExpressionOfOptionalChainRoot(node) { + return isOptionalChainRoot(node.parent) && node.parent.expression === node; + } + ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot; + /** + * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`: + * + * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`) + * 2. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain) + * 3. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is + * the end of the chain starting at `c?.`) + * 4. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is + * the end of the chain starting at `a?.`) + */ + /* @internal */ + function isOutermostOptionalChain(node) { + return !isOptionalChain(node.parent) // cases 1 and 2 + || isOptionalChainRoot(node.parent) // case 3 + || node !== node.parent.expression; // case 4 + } + ts.isOutermostOptionalChain = isOutermostOptionalChain; + function isNullishCoalesce(node) { + return node.kind === 208 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; + } + ts.isNullishCoalesce = isNullishCoalesce; function isNewExpression(node) { return node.kind === 196 /* NewExpression */; } @@ -15814,11 +16623,6 @@ var ts; return node.kind === 162 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; - /* @internal */ - function isOptionalChainRoot(node) { - return ts.isOptionalChain(node) && !!node.questionDotToken; - } - ts.isOptionalChainRoot = isOptionalChainRoot; /** True if has jsdoc nodes attached to it. */ /* @internal */ // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times @@ -15905,7 +16709,12 @@ var ts; this.checker = checker; } } - function Signature() { } + function Signature(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } function Node(kind, pos, end) { this.pos = pos; this.end = end; @@ -16180,273 +16989,6 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - /** - * Normalize path separators. - */ - function normalizeSlashes(path) { - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - function isVolumeCharacter(charCode) { - return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || - (charCode >= 65 /* A */ && charCode <= 90 /* Z */); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; - if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; - } - return -1; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - // POSIX or UNC - if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; // POSIX: "/" (or non-normalized "\") - var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; // UNC: "//server" or "\\server" - return p1 + 1; // UNC: "//server/" or "\\server\" - } - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) - return 2; // DOS: "c:" (but not "c:d") - } - // URL - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - // relative - return 0; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - // TODO(rbuckton): replace references with `resolvePath` - function normalizePath(path) { - return ts.resolvePath(path); - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - // If the path provided is itself the root, then return it. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = ts.removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - /** - * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArrays([root], rest); - } - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = ts.combinePaths(currentDirectory, path); - var rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - ts.getPathComponents = getPathComponents; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - */ - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var result = ts.createMap(); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { @@ -16463,15 +17005,15 @@ var ts; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { aParts.pop(); bParts.pop(); } - return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; } // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. @@ -16481,229 +17023,8 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); - var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArrays([""], relative, components); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - */ - function ensurePathIsNonModuleName(path) { - return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function getBaseFileName(path, extensions, ignoreCase) { - path = ts.normalizeSlashes(path); - // if the path provided is itself the root, then it has not file name. - var rootLength = ts.getRootLength(path); - if (rootLength === path.length) - return ""; - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - /** - * Combines paths. If a path is absolute, it replaces any previous path. - */ - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = ts.normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = ts.normalizeSlashes(relativePath); - if (!path || ts.getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. - */ - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - var combined = ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : ts.normalizeSlashes(path); - var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.resolvePath = resolvePath; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path) { - if (path.length === 0) - return false; - var ch = path.charCodeAt(path.length - 1); - return ch === 47 /* slash */ || ch === 92 /* backslash */; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - // check path for these segments: '', '.'. '..' - var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - var aRoot = a.substring(0, ts.getRootLength(a)); - var bRoot = b.substring(0, ts.getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0 /* EqualTo */) { - return result; - } - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); - var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_1 = componentComparer(aComponents[i], bComponents[i]); - if (result_1 !== 0 /* EqualTo */) { - return result_1; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - /** - * Performs a case-sensitive comparison of two paths. - */ - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); - var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function isDirectorySeparator(charCode) { - return charCode === 47 /* slash */ || charCode === 92 /* backslash */; - } function stripLeadingDirectorySeparator(s) { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); @@ -16722,10 +17043,6 @@ var ts; return "\\" + match; } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -16801,7 +17118,7 @@ var ts; } // getNormalizedPathComponents includes the separator for the root component. // We need to remove to create our regex correctly. - components[0] = removeTrailingDirectorySeparator(components[0]); + components[0] = ts.removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); } @@ -16863,7 +17180,7 @@ var ts; function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); + var absolutePath = ts.combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), @@ -16892,7 +17209,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -16902,8 +17219,8 @@ var ts; visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) @@ -16930,8 +17247,8 @@ var ts; } for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { visitDirectory(name, absoluteName, depth); @@ -16953,14 +17270,14 @@ var ts; var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") - var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include)); // Append the literal and canonical candidate base paths. includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -16977,9 +17294,9 @@ var ts; var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { // No "*" or "?" in the path - return !hasExtension(absolute) + return !ts.hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -17051,10 +17368,6 @@ var ts; return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJSFileExtension = hasJSFileExtension; - function hasJSOrJsonFileExtension(fileName) { - return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); - } - ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; function hasTSFileExtension(fileName) { return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -17144,14 +17457,9 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); @@ -17194,36 +17502,6 @@ var ts; return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") - extensions = [extensions]; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -18431,6 +18709,9 @@ var ts; function doInYieldAndAwaitContext(func) { return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func); } + function doOutsideOfYieldAndAwaitContext(func) { + return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func); + } function inContext(flags) { return (contextFlags & flags) !== 0; } @@ -22702,18 +22983,7 @@ var ts; node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); - // For instance properties specifically, since they are evaluated inside the constructor, - // we do *not * want to parse yield expressions, so we specifically turn the yield context - // off. The grammar would look something like this: - // - // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; - // - // The checker may still error in the static case to explicitly disallow the yield expression. - node.initializer = ts.hasModifier(node, 32 /* Static */) - ? allowInAnd(parseInitializer) - : doOutsideOfContext(8192 /* YieldContext */ | 4096 /* DisallowInContext */, parseInitializer); + node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer); parseSemicolon(); return finishNode(node); } @@ -23004,7 +23274,7 @@ var ts; parseExpected(87 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(18 /* OpenBraceToken */)) { - node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); }); parseExpected(19 /* CloseBraceToken */); } else { @@ -25066,6 +25336,15 @@ var ts; isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, // Basic { name: "target", @@ -25897,8 +26176,7 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { - var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; + function parseCommandLineWorker(getOptionNameMap, diagnostics, commandLine, readFile) { var options = {}; var fileNames = []; var errors = []; @@ -25925,7 +26203,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); + errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -25961,7 +26239,13 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); + var possibleOption = ts.getSpellingSuggestion(s, ts.optionDeclarations, function (opt) { return "--" + opt.name; }); + if (possibleOption) { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownDidYouMeanDiagnostic, s, possibleOption.name)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownOptionDiagnostic, s)); + } } } else { @@ -26004,11 +26288,13 @@ var ts; parseStrings(args); } } + var compilerOptionsDefaultDiagnostics = { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument + }; function parseCommandLine(commandLine, readFile) { - return parseCommandLineWorker(getOptionNameMap, [ - ts.Diagnostics.Unknown_compiler_option_0, - ts.Diagnostics.Compiler_option_0_expects_an_argument - ], commandLine, readFile); + return parseCommandLineWorker(getOptionNameMap, compilerOptionsDefaultDiagnostics, commandLine, readFile); } ts.parseCommandLine = parseCommandLine; /** @internal */ @@ -26033,10 +26319,11 @@ var ts; function parseBuildCommand(args) { var buildOptionNameMap; var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; - var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ - ts.Diagnostics.Unknown_build_option_0, - ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 - ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + }, args), options = _a.options, projects = _a.fileNames, errors = _a.errors; var buildOptions = options; if (projects.length === 0) { // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." @@ -26058,6 +26345,7 @@ var ts; return { buildOptions: buildOptions, projects: projects, errors: errors }; } ts.parseBuildCommand = parseBuildCommand; + /* @internal */ function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -26066,104 +26354,7 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - /* @internal */ - function printVersion() { - ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); - } - ts.printVersion = printVersion; - /* @internal */ - function printHelp(optionsList, syntaxPrefix) { - if (syntaxPrefix === void 0) { syntaxPrefix = ""; } - var output = []; - // We want to align our "syntax" and "examples" commands to a certain margin. - var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); - // Build up the syntactic skeleton. - var syntax = makePadding(marginLength - syntaxLength); - syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; - output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); - output.push(ts.sys.newLine + ts.sys.newLine); - // Build up the list of examples. - var padding = makePadding(marginLength); - output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); - output.push(padding + "tsc @args.txt" + ts.sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); - output.push(ts.sys.newLine); - output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); - // We want our descriptions to align at the same column in our output, - // so we keep track of the longest option usage string. - marginLength = 0; - var usageColumn = []; // Things like "-d, --declaration" go in here. - var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind - for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { - var option = optionsList_1[_i]; - // If an option lacks a description, - // it is not officially supported. - if (!option.description) { - continue; - } - var usageText_1 = " "; - if (option.shortName) { - usageText_1 += "-" + option.shortName; - usageText_1 += getParamType(option); - usageText_1 += ", "; - } - usageText_1 += "--" + option.name; - usageText_1 += getParamType(option); - usageColumn.push(usageText_1); - var description = void 0; - if (option.name === "lib") { - description = getDiagnosticText(option.description); - var element = option.element; - var typeMap = element.type; - optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); - } - else { - description = getDiagnosticText(option.description); - } - descriptionColumn.push(description); - // Set the new margin for the description column if necessary. - marginLength = Math.max(usageText_1.length, marginLength); - } - // Special case that can't fit in the loop. - var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; - var kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { - var kind = kindsList_1[_a]; - output.push(kind + " "); - } - output.push(ts.sys.newLine); - } - } - for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { - var line = output_1[_b]; - ts.sys.write(line); - } - return; - function getParamType(option) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - } - ts.printHelp = printHelp; + ts.getDiagnosticText = getDiagnosticText; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -26247,19 +26438,28 @@ var ts; name: "compilerOptions", type: "object", elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1 + }, }, { name: "typingOptions", type: "object", elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 + }, }, { name: "typeAcquisition", type: "object", elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 + } }, { name: "extends", @@ -26324,7 +26524,7 @@ var ts; function isRootOptionMap(knownOptions) { return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } - function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; @@ -26341,8 +26541,19 @@ var ts; var textOfKey = ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; - if (keyText && extraKeyDiagnosticMessage && !option) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + if (keyText && extraKeyDiagnostics && !option) { + if (knownOptions) { + var possibleOption = ts.getSpellingSuggestion(keyText, ts.arrayFrom(knownOptions.keys()), ts.identity); + if (possibleOption) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownDidYouMeanDiagnostic, keyText, possibleOption)); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } } var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { @@ -26426,8 +26637,8 @@ var ts; // vs what we set in the json // If need arises, we can modify this interface and callbacks as needed if (option) { - var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; - return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName); } else { return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, @@ -26482,7 +26693,7 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign(__assign({ compilerOptions: __assign(__assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; @@ -26503,12 +26714,12 @@ var ts; return undefined; return specs; } - function matchesSpecs(path, includeSpecs, excludeSpecs) { + function matchesSpecs(path, includeSpecs, excludeSpecs, host) { if (!includeSpecs) return function (_) { return true; }; - var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); - var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); - var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; @@ -26685,6 +26896,35 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + /* @internal */ + function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + var result = {}; + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name in options) { + if (ts.hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; + function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option) { + if (option.type === "list") { + var values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value); + } + } + return value; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -27073,7 +27313,7 @@ var ts; } function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); - convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, compilerOptionsDefaultDiagnostics, errors); if (configFileName) { options.configFilePath = ts.normalizeSlashes(configFileName); } @@ -27085,10 +27325,14 @@ var ts; function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); - convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + var diagnostics = { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1, + }; + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, diagnostics, errors); return options; } - function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnostics, errors) { if (!jsonOptions) { return; } @@ -27099,7 +27343,13 @@ var ts; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } else { - errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + var possibleOption = ts.getSpellingSuggestion(id, optionDeclarations, function (opt) { return opt.name; }); + if (possibleOption) { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownDidYouMeanDiagnostic, id, possibleOption.name)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownOptionDiagnostic, id)); + } } } } @@ -27135,7 +27385,7 @@ var ts; } function normalizeNonListOptionValue(option, basePath, value) { if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + value = ts.getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } @@ -28919,7 +29169,10 @@ var ts; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); - var flowNodeCreated = ts.identity; + function initFlowNode(node) { + ts.Debug.attachFlowNodeDebugInfo(node); + return node; + } var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -28948,6 +29201,7 @@ var ts; var currentReturnTarget; var currentTrueTarget; var currentFalseTarget; + var currentExceptionTarget; var preSwitchCaseFlow; var activeLabels; var hasExplicitReturn; @@ -28983,6 +29237,9 @@ var ts; symbolCount = 0; skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); + // Attach debugging information if necessary + ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); + ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -29005,6 +29262,7 @@ var ts; currentReturnTarget = undefined; currentTrueTarget = undefined; currentFalseTarget = undefined; + currentExceptionTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; emitFlags = 0 /* None */; @@ -29326,11 +29584,11 @@ var ts; blockScopeContainer.locals = undefined; } if (containerFlags & 4 /* IsControlFlowContainer */) { - var saveFlowNodeCreated = flowNodeCreated; var saveCurrentFlow = currentFlow; var saveBreakTarget = currentBreakTarget; var saveContinueTarget = currentContinueTarget; var saveReturnTarget = currentReturnTarget; + var saveExceptionTarget = currentExceptionTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && @@ -29338,7 +29596,7 @@ var ts; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isIIFE) { - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.node = node; } @@ -29346,11 +29604,11 @@ var ts; // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. currentReturnTarget = isIIFE || node.kind === 161 /* Constructor */ ? createBranchLabel() : undefined; + currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = ts.identity; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~2816 /* ReachabilityAndEmitFlags */; @@ -29376,9 +29634,9 @@ var ts; currentBreakTarget = saveBreakTarget; currentContinueTarget = saveContinueTarget; currentReturnTarget = saveReturnTarget; + currentExceptionTarget = saveExceptionTarget; activeLabels = saveActiveLabels; hasExplicitReturn = saveHasExplicitReturn; - flowNodeCreated = saveFlowNodeCreated; } else if (containerFlags & 64 /* IsInterface */) { seenThisKeyword = false; @@ -29519,9 +29777,6 @@ var ts; case 309 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; - case 307 /* JSDocClassTag */: - bindJSDocClassTag(node); - break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 288 /* SourceFile */: { bindEachFunctionsFirst(node.statements); @@ -29561,9 +29816,8 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 103 /* ThisKeyword */ || expr.kind === 101 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && - ts.isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + ts.isOptionalChain(expr); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -29620,10 +29874,10 @@ var ts; return isNarrowableReference(expr); } function createBranchLabel() { - return { flags: 4 /* BranchLabel */, antecedents: undefined }; + return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); } function createLoopLabel() { - return { flags: 8 /* LoopLabel */, antecedents: undefined }; + return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined }); } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag @@ -29642,36 +29896,32 @@ var ts; if (!expression) { return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - if (!ts.isOptionalChainRoot(expression.parent)) { - return unreachableFlow; - } + if ((expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) && + !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) { + return unreachableFlow; } if (!isNarrowingExpression(expression)) { return antecedent; } setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: flags, antecedent: antecedent, node: expression }); + return initFlowNode({ flags: flags, antecedent: antecedent, node: expression }); } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { - return antecedent; - } setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd }); + return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd }); } - function createFlowAssignment(antecedent, node) { + function createFlowMutation(flags, antecedent, node) { setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 16 /* Assignment */, antecedent: antecedent, node: node }); + var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node }); + if (currentExceptionTarget) { + addAntecedent(currentExceptionTarget, result); + } + return result; } function createFlowCall(antecedent, node) { setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 512 /* Call */, antecedent: antecedent, node: node }); - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }); + return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node }); } function finishFlowLabel(flow) { var antecedents = flow.antecedents; @@ -29731,7 +29981,7 @@ var ts; } function bindCondition(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); - if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && isOutermostOptionalChain(node))) { + if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -29862,87 +30112,56 @@ var ts; } function bindTryStatement(node) { var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - var tryPriors = []; - var oldFlowNodeCreated = flowNodeCreated; - // We hook the creation of all flow nodes within the `try` scope and store them so we can add _all_ of them - // as possible antecedents of the start of the `catch` or `finally` blocks. - // Don't bother intercepting the call if there's no finally or catch block that needs the information - if (node.catchClause || node.finallyBlock) { - flowNodeCreated = function (node) { return (tryPriors.push(node), node); }; - } + // We conservatively assume that *any* code in the try block can cause an exception, but we only need + // to track code that causes mutations (because only mutations widen the possible control flow type of + // a variable). The currentExceptionTarget is the target label for control flows that result from + // exceptions. We add all mutation flow nodes as antecedents of this label such that we can analyze them + // as possible antecedents of the start of catch or finally blocks. Furthermore, we add the current + // control flow to represent exceptions that occur before any mutations. + var saveExceptionTarget = currentExceptionTarget; + currentExceptionTarget = createBranchLabel(); + addAntecedent(currentExceptionTarget, currentFlow); bind(node.tryBlock); - flowNodeCreated = oldFlowNodeCreated; addAntecedent(preFinallyLabel, currentFlow); var flowAfterTry = currentFlow; var flowAfterCatch = unreachableFlow; if (node.catchClause) { - currentFlow = preTryFlow; - if (tryPriors.length) { - var preCatchFlow = createBranchLabel(); - addAntecedent(preCatchFlow, currentFlow); - for (var _i = 0, tryPriors_1 = tryPriors; _i < tryPriors_1.length; _i++) { - var p = tryPriors_1[_i]; - addAntecedent(preCatchFlow, p); - } - currentFlow = finishFlowLabel(preCatchFlow); - } + // Start of catch clause is the target of exceptions from try block. + currentFlow = finishFlowLabel(currentExceptionTarget); + // The currentExceptionTarget now represents control flows from exceptions in the catch clause. + // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block + // acts like a second try block. + currentExceptionTarget = createBranchLabel(); + addAntecedent(currentExceptionTarget, currentFlow); bind(node.catchClause); addAntecedent(preFinallyLabel, currentFlow); flowAfterCatch = currentFlow; } + var exceptionTarget = finishFlowLabel(currentExceptionTarget); + currentExceptionTarget = saveExceptionTarget; if (node.finallyBlock) { - // We add the nodes within the `try` block to the `finally`'s antecedents if there's no catch block - // (If there is a `catch` block, it will have all these antecedents instead, and the `finally` will - // have the end of the `try` block and the end of the `catch` block) - var preFinallyPrior = preTryFlow; - if (!node.catchClause) { - if (tryPriors.length) { - var preFinallyFlow_1 = createBranchLabel(); - addAntecedent(preFinallyFlow_1, preTryFlow); - for (var _a = 0, tryPriors_2 = tryPriors; _a < tryPriors_2.length; _a++) { - var p = tryPriors_2[_a]; - addAntecedent(preFinallyFlow_1, p); - } - preFinallyPrior = finishFlowLabel(preFinallyFlow_1); - } - } - // in finally flow is combined from pre-try/flow from try/flow from catch - // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable - // also for finally blocks we inject two extra edges into the flow graph. - // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it - // second -> edge that represents post-finally flow. - // these edges are used in following scenario: - // let a; (1) - // try { a = someOperation(); (2)} - // finally { (3) console.log(a) } (4) - // (5) a - // flow graph for this case looks roughly like this (arrows show ): - // (1-pre-try-flow) <--.. <-- (2-post-try-flow) - // ^ ^ - // |*****(3-pre-finally-label) -----| - // ^ - // |-- ... <-- (4-post-finally-label) <--- (5) - // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account - // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) - // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable - // Simply speaking code inside finally block is treated as reachable as pre-try-flow - // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. - // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from - // final flows of these blocks without taking pre-try flow into account. - // - // extra edges that we inject allows to control this behavior - // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }; + // Possible ways control can reach the finally block: + // 1) Normal completion of try block of a try-finally or try-catch-finally + // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally + // 3) Exception in try block of a try-finally + // 4) Exception in catch block of a try-catch-finally + // When analyzing a control flow graph that starts inside a finally block we want to consider all + // four possibilities above. However, when analyzing a control flow graph that starts outside (past) + // the finally block, we only want to consider the first two (if we're past a finally block then it + // must have completed normally). To make this possible, we inject two extra nodes into the control + // flow graph: An after-finally with an antecedent of the control flow at the end of the finally + // block, and a pre-finally with an antecedent that represents all exceptional control flows. The + // 'lock' property of the pre-finally references the after-finally, and the after-finally has a + // boolean 'locked' property that we set to true when analyzing a control flow that contained the + // the after-finally node. When the lock associated with a pre-finally is locked, the antecedent of + // the pre-finally (i.e. the exceptional control flows) are skipped. + var preFinallyFlow = initFlowNode({ flags: 4096 /* PreFinally */, antecedent: exceptionTarget, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); - // if flow after finally is unreachable - keep it - // otherwise check if flows after try and after catch are unreachable - // if yes - convert current flow to unreachable - // i.e. - // try { return "1" } finally { console.log(1); } - // console.log(2); // this line should be unreachable even if flow falls out of finally block + // If the end of the finally block is reachable, but the end of the try and catch blocks are not, + // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should + // result in an unreachable current control flow. if (!(currentFlow.flags & 1 /* Unreachable */)) { if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow @@ -29951,7 +30170,7 @@ var ts; } } if (!(currentFlow.flags & 1 /* Unreachable */)) { - var afterFinallyFlow = flowNodeCreated({ flags: 8192 /* AfterFinally */, antecedent: currentFlow }); + var afterFinallyFlow = initFlowNode({ flags: 8192 /* AfterFinally */, antecedent: currentFlow }); preFinallyFlow.lock = afterFinallyFlow; currentFlow = afterFinallyFlow; } @@ -29985,6 +30204,7 @@ var ts; var savedSubtreeTransformFlags = subtreeTransformFlags; subtreeTransformFlags = 0; var clauses = node.clauses; + var isNarrowingSwitch = isNarrowingExpression(node.parent.expression); var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { var clauseStart = i; @@ -29993,14 +30213,14 @@ var ts; i++; } var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; @@ -30064,7 +30284,7 @@ var ts; } function bindAssignmentTargetFlow(node) { if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); + currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } else if (node.kind === 191 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { @@ -30145,7 +30365,7 @@ var ts; if (operator === 62 /* EqualsToken */ && node.left.kind === 194 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } } @@ -30181,7 +30401,7 @@ var ts; } } else { - currentFlow = createFlowAssignment(currentFlow, node); + currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } } function bindVariableDeclarationFlow(node) { @@ -30203,12 +30423,9 @@ var ts; addDeclarationToSymbol(host.symbol, host, 32 /* Class */); } } - function isOutermostOptionalChain(node) { - return !ts.isOptionalChain(node.parent) || ts.isOptionalChainRoot(node.parent) || node !== node.parent.expression; - } function bindOptionalExpression(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); - if (!ts.isOptionalChain(node) || isOutermostOptionalChain(node)) { + if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -30246,7 +30463,7 @@ var ts; currentFlow = finishFlowLabel(preChainLabel); } doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget); - if (isOutermostOptionalChain(node)) { + if (ts.isOutermostOptionalChain(node)) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -30290,7 +30507,7 @@ var ts; if (node.expression.kind === 193 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } } @@ -30590,7 +30807,7 @@ var ts; var host = ts.getJSDocHost(typeAlias); container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); var declName = ts.getNameOfDeclaration(typeAlias); @@ -30603,7 +30820,12 @@ var ts; switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: - container = file; + if (!ts.isExternalOrCommonJsModule(file)) { + container = undefined; + } + else { + container = file; + } break; case 4 /* ThisProperty */: container = declName.parent.expression; @@ -30617,7 +30839,9 @@ var ts; case 0 /* None */: return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration"); } - declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + if (container) { + declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + } container = oldContainer; } } @@ -31013,6 +31237,8 @@ var ts; case 302 /* JSDocTypeLiteral */: case 185 /* MappedType */: return bindAnonymousTypeWorker(node); + case 307 /* JSDocClassTag */: + return bindJSDocClassTag(node); case 192 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); case 200 /* FunctionExpression */: @@ -31232,7 +31458,8 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -31248,7 +31475,7 @@ var ts; constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); } } - if (constructorSymbol) { + if (constructorSymbol && constructorSymbol.valueDeclaration) { // Declare a 'member' if the container is an ES5 class or ES6 constructor constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); // It's acceptable for multiple 'this' assignments of the same identifier to occur @@ -31321,6 +31548,10 @@ var ts; } function bindObjectDefinePrototypeProperty(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol) { + // Ensure the namespace symbol becomes class-like + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** @@ -31395,7 +31626,7 @@ var ts; } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); } return namespaceSymbol; @@ -32044,7 +32275,8 @@ var ts; || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type - || !node.body) { + || !node.body + || node.questionToken) { transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax @@ -32081,7 +32313,7 @@ var ts; function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 1048576 /* ContainsClassFields */; // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax. - if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type) { + if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken) { transformFlags |= 1 /* AssertTypeScript */; } // Hoisted variables related to class properties should live within the TypeScript class wrapper. @@ -32886,6 +33118,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 7] = "ResolvedTypeArguments"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -32896,12 +33129,6 @@ var ts; CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; })(CheckMode || (CheckMode = {})); - var ContextFlags; - (function (ContextFlags) { - ContextFlags[ContextFlags["None"] = 0] = "None"; - ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; - ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; - })(ContextFlags || (ContextFlags = {})); var AccessFlags; (function (AccessFlags) { AccessFlags[AccessFlags["None"] = 0] = "None"; @@ -33035,14 +33262,12 @@ var ts; undefinedSymbol.declarations = []; var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); globalThisSymbol.exports = globals; + globalThisSymbol.declarations = []; globals.set(globalThisSymbol.escapedName, globalThisSymbol); var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; - // This object is reused for `checkOptionalExpression` return values to avoid frequent GC due to nursery object allocations. - // This object represents a pool-size of 1. - var pooledOptionalTypeResult = { isOptional: false, type: undefined }; // for public members that accept a Node or one of its subtypes, we must guard against // synthetic nodes created during transformations by calling `getParseTreeNode`. // for most of these, we perform the guard only on `checker` to avoid any possible @@ -33161,9 +33386,9 @@ var ts; }, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (nodeIn) { + getContextualType: function (nodeIn, contextFlags) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); @@ -33212,7 +33437,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments), getAmbientModules: getAmbientModules, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { @@ -33341,10 +33566,10 @@ var ts; var errorType = createIntrinsicType(1 /* Any */, "error"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 262144 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 262144 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -33370,7 +33595,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", 1048576 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -33388,7 +33613,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 |= 1048576 /* NonInferrableType */; + anyFunctionType.objectFlags |= 2097152 /* 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); @@ -33397,10 +33622,10 @@ var ts; markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances var noIterationTypes = { @@ -33553,7 +33778,7 @@ var ts; var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } } } @@ -33563,7 +33788,7 @@ var ts; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -35041,7 +35266,7 @@ var ts; var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0); var symbol; if (name.kind === 75 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { @@ -35153,7 +35378,12 @@ var ts; return undefined; } var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl); - return init && getSymbolOfNode(init) || undefined; + if (init) { + var initSymbol = getSymbolOfNode(init); + if (initSymbol) { + return mergeJSSymbols(initSymbol, symbol); + } + } } function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); @@ -35580,8 +35810,8 @@ var ts; } function findConstructorDeclaration(node) { var members = node.members; - for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { - var member = members_2[_i]; + for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { + var member = members_3[_i]; if (member.kind === 161 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } @@ -36004,7 +36234,7 @@ var ts; // Type Reference or TypeAlias entity = Identifier meaning = 788968 /* Type */; } - var firstIdentifier = getFirstIdentifier(entityName); + var firstIdentifier = ts.getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { @@ -36496,8 +36726,6 @@ var ts; else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && ts.isClassLike(type.symbol.valueDeclaration) && - // Use `import` types for refs to other scopes, only anonymize something defined in the same scope - ts.findAncestor(type.symbol.valueDeclaration, function (d) { return d === ts.getSourceFileOfNode(context.enclosingDeclaration); }) && !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } @@ -36658,9 +36886,9 @@ var ts; } } } - var propertyName = symbolToName(propertySymbol, context, 111551 /* Value */, /*expectsIdentifier*/ true); - context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; + var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */); @@ -36859,7 +37087,7 @@ var ts; if (!context.tracker.trackSymbol) return; // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(accessExpression); + var firstIdentifier = ts.getFirstIdentifier(accessExpression); var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */); @@ -37225,22 +37453,34 @@ var ts; } } } + function isSingleQuotedStringNamed(d) { + var name = ts.getNameOfDeclaration(d); + if (name && ts.isStringLiteral(name) && (name.singleQuote || + (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")))) { + return true; + } + return false; + } function getPropertyNameNodeForSymbol(symbol, context) { - var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context); + var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed); + var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote); if (fromNameType) { return fromNameType; } + if (ts.isKnownSymbol(symbol)) { + return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3))); + } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); - return createPropertyNameNodeForIdentifierOrLiteral(rawName); + return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote); } // See getNameForSymbolFromNameType for a stringy equivalent - function getPropertyNameNodeForSymbolFromNameType(symbol, context) { + function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) { var nameType = symbol.nameType; if (nameType) { if (nameType.flags & 384 /* StringOrNumberLiteral */) { var name = "" + nameType.value; if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { - return ts.createLiteral(name); + return ts.createLiteral(name, !!singleQuote); } if (isNumericLiteralName(name) && ts.startsWith(name, "-")) { return ts.createComputedPropertyName(ts.createLiteral(+name)); @@ -37252,8 +37492,8 @@ var ts; } } } - function createPropertyNameNodeForIdentifierOrLiteral(name) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name); + function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -37293,7 +37533,7 @@ var ts; var visitedSymbols = ts.createMap(); var deferredPrivates; var oldcontext = context; - context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.mapMap(symbolTable, function (_symbol, name) { return [ts.unescapeLeadingUnderscores(name), true]; }), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { + context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it @@ -37311,6 +37551,10 @@ var ts; context.usedSymbolNames.set(name, true); }); } + ts.forEachEntry(symbolTable, function (symbol, name) { + var baseName = ts.unescapeLeadingUnderscores(name); + void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames` + }); var addingDeclare = !bundled; var exportEquals = symbolTable.get("export=" /* ExportEquals */); if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) { @@ -37502,7 +37746,11 @@ var ts; isPrivate = true; } var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0); - if (symbol.flags & 16 /* Function */) { + var isConstMergedWithNS = symbol.flags & 1536 /* Module */ && + symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && + symbol.escapedName !== "export=" /* ExportEquals */; + var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol); + if (symbol.flags & 16 /* Function */ || isConstMergedWithNSPrintableAsSignatureMerge) { serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } if (symbol.flags & 524288 /* TypeAlias */) { @@ -37513,7 +37761,8 @@ var ts; if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) - && !(symbol.flags & 32 /* Class */)) { + && !(symbol.flags & 32 /* Class */) + && !isConstMergedWithNSPrintableAsSignatureMerge) { serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags); } if (symbol.flags & 384 /* Enum */) { @@ -37530,7 +37779,7 @@ var ts; serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } } - if (symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */)) { + if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) { serializeModule(symbol, symbolName, modifierFlags); } if (symbol.flags & 64 /* Interface */) { @@ -37558,7 +37807,10 @@ var ts; } } function includePrivateSymbol(symbol) { + if (ts.some(symbol.declarations, ts.isParameterDeclaration)) + return; ts.Debug.assertDefined(deferredPrivates); + getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol deferredPrivates.set("" + getSymbolId(symbol), symbol); } function isExportingScope(enclosingDeclaration) { @@ -37617,8 +37869,14 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } + function getNamespaceMembersForSerialization(symbol) { + return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + } + function isTypeOnlyNamespace(symbol) { + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); }); + } function serializeModule(symbol, symbolName, modifierFlags) { - var members = !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + var members = getNamespaceMembersForSerialization(symbol); // Split NS members up by declaration - members whose parent symbol is the ns symbol vs those whose is not (but were added in later via merging) var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; }); var realMembers = locationMap.get("real") || ts.emptyArray; @@ -37628,17 +37886,20 @@ var ts; // so we don't even have placeholders to fill in. if (ts.length(realMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, /*suppressNewPrivateContext*/ false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); } if (ts.length(mergedMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - ts.forEach(mergedMembers, includePrivateSymbol); var nsBody = ts.createModuleBlock([ts.createExportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); - return ts.createExportSpecifier(name === localName ? undefined : localName, name); + var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); + includePrivateSymbol(target || s); + var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; + return ts.createExportSpecifier(name === targetName ? undefined : targetName, name); })))]); addResult(ts.createModuleDeclaration( /*decorators*/ undefined, @@ -37839,7 +38100,11 @@ var ts; case 254 /* ImportClause */: addResult(ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), + // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned + // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag + // In such cases, the `target` refers to the module itself already + ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 255 /* NamespaceImport */: addResult(ts.createImportDeclaration( @@ -37851,7 +38116,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([ ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName)) - ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 261 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, @@ -37865,6 +38130,7 @@ var ts; serializeMaybeAliasAssignment(symbol); break; case 208 /* BinaryExpression */: + case 193 /* PropertyAccessExpression */: // Could be best encoded as though an export specifier or as though an export assignment // If name is default or export=, do an export assignment // Otherwise do an export specifier @@ -37875,10 +38141,6 @@ var ts; serializeExportSpecifier(localName, targetName); } break; - case 193 /* PropertyAccessExpression */: - // A PAE alias is _always_ going to exist as an append to a top-level export, where our top level - // handling should always be sufficient to encode the export action itself - break; default: return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!"); } @@ -37902,7 +38164,8 @@ var ts; var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol); // serialize what the alias points to, preserve the declaration's initializer var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); - if (target) { + // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const + if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) { // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it // eg, `namespace A { export class B {} }; exports = A.B;` // Technically, this is all that's required in the case where the assignment is an entity name expression @@ -37977,6 +38240,7 @@ var ts; return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) && !getIndexInfoOfType(typeToSerialize, 0 /* String */) && !getIndexInfoOfType(typeToSerialize, 1 /* Number */) && + !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK !getDeclarationWithTypeAnnotation(hostSymbol) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && @@ -38120,7 +38384,7 @@ var ts; return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = getFirstIdentifier(node); + var leftmost = ts.getFirstIdentifier(node); var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); if (sym) { includePrivateSymbol(sym); @@ -38250,11 +38514,8 @@ var ts; return context.remappedSymbolNames.get("" + getSymbolId(symbol)); } } - if (input === "default" /* Default */) { - input = "_default"; - } - else if (input === "export=" /* ExportEquals */) { - input = "_exports"; + if (symbol) { + input = getNameCandidateWorker(symbol, input); } var i = 0; var original = input; @@ -38268,17 +38529,28 @@ var ts; } return input; } - function getInternalSymbolName(symbol, localName) { - if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) { - return context.remappedSymbolNames.get("" + getSymbolId(symbol)); - } + function getNameCandidateWorker(symbol, localName) { if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) { var flags = context.flags; context.flags |= 16777216 /* InInitialEntityName */; var nameCandidate = getNameOfSymbolAsWritten(symbol, context); context.flags = flags; - localName = ts.isIdentifierText(nameCandidate, languageVersion) && !ts.isStringANonContextualKeyword(nameCandidate) ? nameCandidate : getUnusedName("_default", symbol); + localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate; } + if (localName === "default" /* Default */) { + localName = "_default"; + } + else if (localName === "export=" /* ExportEquals */) { + localName = "_exports"; + } + localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_"); + return localName; + } + function getInternalSymbolName(symbol, localName) { + if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) { + return context.remappedSymbolNames.get("" + getSymbolId(symbol)); + } + localName = getNameCandidateWorker(symbol, localName); // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up context.remappedSymbolNames.set("" + getSymbolId(symbol), localName); return localName; @@ -38543,7 +38815,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); + var firstIdentifier = ts.getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); var id = importSymbol && "" + getSymbolId(importSymbol); if (importSymbol && !visited.has(id)) { @@ -38607,6 +38879,8 @@ var ts; return !!target.immediateBaseConstraint; case 6 /* JSDocTypeReference */: return !!getSymbolLinks(target).resolvedJSDocType; + case 7 /* ResolvedTypeArguments */: + return !!target.resolvedTypeArguments; } return ts.Debug.assertNever(propertyName); } @@ -38692,7 +38966,9 @@ var ts; } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); - return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + result.objectFlags |= 131072 /* ObjectRestType */; + return result; } // Determine the control flow type associated with a destructuring declaration or assignment. The following // forms of destructuring are possible: @@ -39078,23 +39354,23 @@ var ts; kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); - var members_3 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_3); + var members_4 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_3.has(name)) { + if (members_4.has(name)) { var exportedMember = exportedType_1.members.get(name); var union = createSymbol(s.flags | exportedMember.flags, name); union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_3.set(name, union); + members_4.set(name, union); } else { - members_3.set(name, s); + members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag return result; } @@ -39154,7 +39430,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -39294,16 +39570,12 @@ var ts; if (!declaration.statements.length) { return emptyObjectType; } - var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); - if (type_1.flags & 524288 /* Object */) { - return getRegularTypeOfObjectLiteral(type_1); - } - return type_1; + return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression))); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39371,7 +39643,7 @@ var ts; } if (!popTypeResolution()) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39454,7 +39726,9 @@ var ts; } else { ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -39500,11 +39774,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_2; + return type_1; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -39690,6 +39964,7 @@ var ts; // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 245 /* InterfaceDeclaration */); + ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -39720,7 +39995,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length === 1) { var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -40427,8 +40702,8 @@ var ts; var decl = _a[_i]; var members = ts.getMembersOfDeclaration(decl); if (members) { - for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { - var member = members_4[_b]; + for (var _b = 0, members_5 = members; _b < members_5.length; _b++) { + var member = members_5[_b]; if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { lateBindMember(symbol, earlySymbols, lateSymbols, member); } @@ -40557,8 +40832,8 @@ var ts; var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + var sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -40566,15 +40841,13 @@ var ts; sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; } function cloneSignature(sig) { var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -40586,13 +40859,25 @@ var ts; result.mapper = undefined; return result; } - function createOptionalCallSignature(signature) { + function getOptionalCallSignature(signature, callChainFlags) { + if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) { + return signature; + } + if (!signature.optionalCallSignatureCache) { + signature.optionalCallSignatureCache = {}; + } + var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer"; + return signature.optionalCallSignatureCache[key] + || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags)); + } + function createOptionalCallSignature(signature, callChainFlags) { + ts.Debug.assert(callChainFlags === 4 /* IsInnerCallChain */ || callChainFlags === 8 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both."); var result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= callChainFlags; return result; } function getExpandedParameters(sig) { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { var restIndex_1 = sig.parameters.length - 1; var restParameter = sig.parameters[restIndex_1]; var restType = getTypeOfSymbol(restParameter); @@ -40617,7 +40902,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJSFile(baseTypeNode); @@ -40781,11 +41066,9 @@ var ts; var params = combineUnionParameters(left, right); var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - var hasRestParam = left.hasRestParameter || right.hasRestParameter; - var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */); result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); return result; } @@ -40958,7 +41241,7 @@ var ts; var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray; if (symbol.flags & 16 /* Function */) { constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) : undefined; })); } if (!constructSignatures.length) { @@ -41464,8 +41747,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_3 = types_6[_i]; - var baseType = getBaseConstraint(type_3); + var type_2 = types_6[_i]; + var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } @@ -41898,7 +42181,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var flags = 0 /* None */; var minArgumentCount = 0; var thisParameter = void 0; var hasThisParameter = false; @@ -41929,7 +42212,7 @@ var ts; parameters.push(paramSymbol); } if (type && type.kind === 186 /* LiteralType */) { - hasLiteralTypes = true; + flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || @@ -41955,9 +42238,11 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1 /* HasRestParameter */; + } links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, - /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -42100,8 +42385,11 @@ var ts; signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, /*wasOptional*/ true); + if (signature.flags & 4 /* IsInnerCallChain */) { + type = addOptionalTypeMarker(type); + } + else if (signature.flags & 8 /* IsOuterCallChain */) { + type = getOptionalType(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -42157,7 +42445,7 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, 1 /* Number */); @@ -42374,7 +42662,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 1835008 /* PropagatingFlags */; + return result & 3670016 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -42408,13 +42696,25 @@ var ts; return type; } function getTypeArguments(type) { + var _a, _b; if (!type.resolvedTypeArguments) { + if (!pushTypeResolution(type, 7 /* ResolvedTypeArguments */)) { + return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray; + } var node = type.node; var typeArguments = !node ? ts.emptyArray : node.kind === 168 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : node.kind === 173 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode); - type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + if (popTypeResolution()) { + type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + } + else { + type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray; + error(type.node || currentNode, type.target.symbol + ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves + : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol)); + } } return type.resolvedTypeArguments; } @@ -42531,7 +42831,7 @@ var ts; errorType; } if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) { - var jsdocType = getTypeFromJSAlias(node, symbol); + var jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -42544,18 +42844,30 @@ var ts; return errorType; } /** - * A JSdoc TypeReference may be to a value imported from commonjs. - * These should really be aliases, but this special-case code fakes alias resolution - * by producing a type from a value. + * A JSdoc TypeReference may be to a value, but resolve it as a type anyway. + * Note: If the value is imported from commonjs, it should really be an alias, + * but this function's special-case code fakes alias resolution as well. */ - function getTypeFromJSAlias(node, symbol) { + function getTypeFromJSDocValueReference(node, symbol) { var valueType = getTypeOfSymbol(symbol); - var typeType = valueType.symbol && - valueType.symbol !== symbol && // Make sure this is a commonjs export by checking that symbol -> type -> symbol doesn't roundtrip. - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + var typeType = valueType; + if (symbol.valueDeclaration) { + var decl = ts.getRootDeclaration(symbol.valueDeclaration); + var isRequireAlias = false; + if (ts.isVariableDeclaration(decl) && decl.initializer) { + var expr = decl.initializer; + // skip past entity names, eg `require("x").a.b.c` + while (ts.isPropertyAccessExpression(expr)) { + expr = expr.expression; + } + isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol; + } + var isImportTypeWithQualifier = node.kind === 187 /* ImportType */ && node.qualifier; + if (isRequireAlias || isImportTypeWithQualifier) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable, substitute) { if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === typeVariable) { @@ -42984,7 +43296,7 @@ var ts; if (type === wildcardType) includes |= 4194304 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 262144 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) includes |= 2097152 /* IncludesNonWideningType */; } else { @@ -43111,7 +43423,7 @@ var ts; neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 131072 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -43261,7 +43573,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) & 131072 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -43270,7 +43582,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 131072 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -43299,7 +43611,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 131072 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -44096,7 +44408,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host)) { + while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 137 /* ReadonlyKeyword */) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -44197,7 +44509,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ @@ -44511,7 +44823,7 @@ var ts; // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */); result.target = signature; result.mapper = mapper; return result; @@ -45392,20 +45704,20 @@ var ts; } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, - /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */; } /** * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any` */ function isAnySignature(s) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } /** * See signatureRelatedTo, compareSignaturesIdentical */ - function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) { // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; @@ -45424,6 +45736,9 @@ var ts; var sourceCount = getParameterCount(source); var sourceRestType = getNonArrayRestType(source); var targetRestType = getNonArrayRestType(target); + if (sourceRestType || targetRestType) { + void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers); + } if (sourceRestType && targetRestType && sourceCount !== targetCount) { // We're not able to relate misaligned complex rest parameters return 0 /* False */; @@ -45467,7 +45782,7 @@ var ts; (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); var related = callbacks ? // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is - compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) : + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { @@ -45481,13 +45796,13 @@ var ts; // If a signature resolution is already in-flight, skip issuing a circularity error // here and just use the `any` type directly var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType - : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(target.declaration.symbol) + : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol)) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType - : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(source.declaration.symbol) + : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol)) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); @@ -45674,7 +45989,7 @@ var ts; return true; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var related = relation.get(getRelationKey(source, target, relation)); + var related = relation.get(getRelationKey(source, target, /*isIntersectionConstituent*/ false, relation)); if (related !== undefined) { return !!(related & 1 /* Succeeded */); } @@ -46045,7 +46360,7 @@ var ts; // and we need to handle "each" relations before "some" relations for the same kind of type. if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), isIntersectionConstituent) : + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); } else { @@ -46083,7 +46398,7 @@ var ts; // // - For a primitive type or type parameter (such as 'number = A & B') there is no point in // breaking the intersection apart. - result = someTypeRelatedToType(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ true); + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { @@ -46196,7 +46511,7 @@ var ts; // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) - if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration)) { + if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) { // Note that extraneous children (as in `extra`) don't pass this check, // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute. errorNode = prop.valueDeclaration.name; @@ -46207,7 +46522,7 @@ var ts; // use the property's value declaration if the property is assigned inside the literal itself var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; - if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) { var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; @@ -46367,14 +46682,14 @@ var ts; } return result; } - function someTypeRelatedToType(source, target, reportErrors, isIntersectionConstituent) { + function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; for (var i = 0; i < len; i++) { - var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, isIntersectionConstituent); + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { return related; } @@ -46462,7 +46777,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, relation); + var id = getRelationKey(source, target, isIntersectionConstituent, relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -47356,7 +47671,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, incompatibleReporter, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, incompatibleReporter, isRelatedTo, reportUnreliableMarkers); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -47648,17 +47963,18 @@ var ts; * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. * For other cases, the types ids are used. */ - function getRelationKey(source, target, relation) { + function getRelationKey(source, target, isIntersectionConstituent, relation) { if (relation === identityRelation && source.id > target.id) { var temp = source; source = target; target = temp; } + var intersection = isIntersectionConstituent ? "&" : ""; if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { var typeParameters = []; - return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + intersection; } - return source.id + "," + target.id; + return source.id + "," + target.id + intersection; } // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. @@ -47709,7 +48025,7 @@ var ts; // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`). function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 524288 /* Object */) { + if (depth >= 5 && type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { var symbol = type.symbol; if (symbol) { var count = 0; @@ -48084,37 +48400,19 @@ var ts; function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type) { + return type !== optionalType; + } function removeOptionalTypeMarker(type) { - return strictNullChecks ? filterType(type, function (t) { return t !== optionalType; }) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } - function propagateOptionalTypeMarker(type, wasOptional) { - return wasOptional ? addOptionalTypeMarker(type) : type; + function propagateOptionalTypeMarker(type, node, wasOptional) { + return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional, type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - function checkOptionalExpression(parent, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var isOptional = false; - var type = checkExpression(expression); - if (ts.isOptionalChain(parent)) { - if (parent.questionDotToken) { - // If we have a questionDotToken then we are an OptionalExpression and should remove `null` and - // `undefined` from the type and add the optionalType to the result, if needed. - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - // If we do not have a questionDotToken, then we are an OptionalChain and we remove the optionalType and - // indicate whether we need to add optionalType back into the result. - var nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType, expression) { + return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } /** * Is source potentially coercible to target type under `==`. @@ -48268,14 +48566,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 */ | 1048576 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* 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) & 786432 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -48320,7 +48618,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 262144 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -48346,7 +48644,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) & 262144 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -48426,7 +48724,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 262144 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -48543,7 +48841,7 @@ var ts; return !!(type.flags & 63176704 /* Instantiable */ || 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 */ || + objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { @@ -48598,7 +48896,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) & 1048576 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }); } function createReverseMappedType(source, target, constraint) { @@ -48749,10 +49047,7 @@ var ts; // inferring a type parameter constraint. Instead, make a lower priority inference from // the full source to whatever remains in the target. For example, when inferring from // string to 'string | T', make a lower priority inference of string for T. - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, 1 /* NakedTypeVariable */); return; } source = getUnionType(sources); @@ -48785,7 +49080,7 @@ 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) & 1048576 /* NonInferrableType */ || source === silentNeverType || (priority & 16 /* ReturnType */ && (source === autoType || source === autoArrayType))) { + if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === silentNeverType || (priority & 16 /* ReturnType */ && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -48852,10 +49147,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - var savePriority = priority; - priority |= 32 /* LiteralKeyof */; - inferFromTypes(empty, target.type); - priority = savePriority; + inferWithPriority(empty, target.type, 32 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -48907,6 +49199,12 @@ var ts; } } } + function inferWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -48972,6 +49270,18 @@ var ts; } return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types) { + var typeVariable; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var type = types_13[_i]; + var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } function inferToMultipleTypes(source, targets, targetFlags) { var typeVariableCount = 0; if (targetFlags & 1048576 /* Union */) { @@ -49001,6 +49311,16 @@ var ts; } } } + if (typeVariableCount === 0) { + // If every target is an intersection of types containing a single naked type variable, + // make a lower priority inference to that type variable. This handles inferring from + // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T. + var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */); + } + return; + } // If the target has a single naked type variable and no inference circularities were // encountered above (meaning we explored the types fully), create a union of the source // types from which no inferences have been made so far and infer from that union to the @@ -49032,15 +49352,12 @@ var ts; // we want to infer string for T, not Promise | string. For intersection types // we only infer to single naked type variables. if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) { - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) { var t = targets_4[_b]; if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, 1 /* NakedTypeVariable */); } } - priority = savePriority; } } function inferToMappedType(source, target, constraintType) { @@ -49061,14 +49378,12 @@ var ts; if (inference && !inference.isFixed) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - var savePriority = priority; // 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). - priority |= ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? - 4 /* PartialHomomorphicMappedType */ : 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? + 4 /* PartialHomomorphicMappedType */ : + 2 /* HomomorphicMappedType */); } } return true; @@ -49076,10 +49391,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. - var savePriority = priority; - priority |= 8 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, 8 /* 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 @@ -49188,7 +49500,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 1048576 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -49457,6 +49769,15 @@ var ts; } return false; } + function optionalChainContainsReference(source, target) { + while (ts.isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property // a possible discriminant if its type differs in the constituents of containing union type, and if every @@ -49577,8 +49898,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; result |= getTypeFacts(t); } return result; @@ -49947,8 +50268,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -50029,9 +50350,18 @@ var ts; // expressions are potential type predicate function calls. In order to avoid triggering // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. - var funcType = node.parent.kind === 225 /* ExpressionStatement */ ? getTypeOfDottedName(node.expression, /*diagnostic*/ undefined) : - node.expression.kind !== 101 /* SuperKeyword */ ? checkOptionalExpression(node, node.expression).type : - undefined; + var funcType = void 0; + if (node.parent.kind === 225 /* ExpressionStatement */) { + funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); + } + else if (node.expression.kind !== 101 /* SuperKeyword */) { + if (ts.isOptionalChain(node)) { + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */); var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -50044,6 +50374,13 @@ var ts; return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */); } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { + return callExpression.arguments[predicate.parameterIndex]; + } + var invokedExpression = ts.skipParentheses(callExpression.expression); + return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined; + } function reportFlowControlError(node) { var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); var sourceFile = ts.getSourceFileOfNode(node); @@ -50059,6 +50396,11 @@ var ts; function isUnlockedReachableFlowNode(flow) { return !(flow.flags & 4096 /* PreFinally */ && flow.lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); } + function isFalseExpression(expr) { + var node = ts.skipParentheses(expr); + return node.kind === 90 /* FalseKeyword */ || node.kind === 208 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); + } function isReachableFlowNodeWorker(flow, noCacheCheck) { while (true) { if (flow === lastFlowNode) { @@ -50078,8 +50420,17 @@ var ts; } else if (flags & 512 /* Call */) { var signature = getEffectsSignature(flow.node); - if (signature && getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { - return false; + if (signature) { + var predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3 /* AssertsIdentifier */) { + var predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { + return false; + } } flow = flow.antecedent; } @@ -50313,6 +50664,9 @@ var ts; } function narrowTypeByAssertion(type, expr) { var node = ts.skipParentheses(expr); + if (node.kind === 90 /* FalseKeyword */) { + return unreachableNeverType; + } if (node.kind === 208 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); @@ -50331,7 +50685,7 @@ var ts; var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : - predicate.kind === 3 /* AssertsIdentifier */ ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -50402,17 +50756,24 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } else if (expr.kind === 203 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); + } + else if (expr.kind === 203 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -50420,6 +50781,7 @@ var ts; var antecedentTypes = []; var subtypeReduction = false; var seenIncomplete = false; + var bypassFlow; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; if (antecedent.flags & 4096 /* PreFinally */ && antecedent.lock.locked) { @@ -50428,6 +50790,11 @@ var ts; // in this case we should ignore this branch. continue; } + if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) { + // The antecedent is the bypass branch of a potentially exhaustive switch statement. + bypassFlow = antecedent; + continue; + } var flowType = getTypeAtFlowNode(antecedent); var type = getTypeFromFlowType(flowType); // If the type at a particular antecedent path is the declared type and the @@ -50448,6 +50815,25 @@ var ts; seenIncomplete = true; } } + if (bypassFlow) { + var flowType = getTypeAtFlowNode(bypassFlow); + var type = getTypeFromFlowType(flowType); + // If the bypass flow contributes a type we haven't seen yet and the switch statement + // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase + // the risk of circularities, we only want to perform them when they make a difference. + if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) { + if (type === declaredType && declaredType === initialType) { + return type; + } + antecedentTypes.push(type); + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + } return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { @@ -50554,6 +50940,9 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } @@ -50602,6 +50991,14 @@ var ts; if (isMatchingReference(reference, right_1)) { return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + } + else if (optionalChainContainsReference(right_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left_1, declaredType)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } @@ -50625,6 +51022,15 @@ var ts; } return type; } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + // We are in a branch of obj?.foo === value or obj?.foo !== value. We remove undefined and null from + // the type of obj if (a) the operator is === and the type of value doesn't include undefined or (b) the + // operator is !== and the type of value is undefined. + var effectiveTrue = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */ ? assumeTrue : !assumeTrue; + var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */; + var valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? 262144 /* EQUndefinedOrNull */ : 65536 /* EQUndefined */)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* Any */) { return type; @@ -50672,8 +51078,14 @@ var ts; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands + if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, target)) { @@ -50681,9 +51093,6 @@ var ts; } return type; } - if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } @@ -50716,6 +51125,10 @@ var ts; return type; } } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { + var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify // values with unit types, except for the case where @@ -50848,6 +51261,9 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' // references might reference a different 'y' property. However, we make an exception @@ -50920,39 +51336,28 @@ var ts; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + var predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (ts.isAccessExpression(invokedExpression) && predicate.type) { - var possibleReference = ts.skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if (ts.isOptionalChainRoot(expr.parent) || + if (ts.isExpressionOfOptionalChainRoot(expr) || ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -51233,7 +51638,24 @@ var ts; } } else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { - error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + var diag = error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // See GH:32846 - if the user is using a variable whose type is () => T1 | ... | undefined + // they may have meant to specify the type as (() => T1 | ...) | undefined + // This is assumed if: the type is a FunctionType, the return type is a Union, the last constituent of + // the union is `undefined` + if (type.symbol && type.symbol.declarations.length === 1 && ts.isFunctionTypeNode(type.symbol.declarations[0])) { + var funcTypeNode = type.symbol.declarations[0]; + var returnType = getReturnTypeFromAnnotation(funcTypeNode); + if (returnType && returnType.flags & 1048576 /* Union */) { + var unionTypes_3 = funcTypeNode.type.types; + if (unionTypes_3 && unionTypes_3[unionTypes_3.length - 1].kind === 145 /* UndefinedKeyword */) { + var parenedFuncType = ts.getMutableClone(funcTypeNode); + // Highlight to the end of the second to last constituent of the union + parenedFuncType.end = unionTypes_3[unionTypes_3.length - 2].end; + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(parenedFuncType, ts.Diagnostics.Did_you_mean_to_parenthesize_this_function_type)); + } + } + } // Return the declared type to reduce follow-on errors return type; } @@ -52013,18 +52435,22 @@ var ts; return undefined; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget, arg) { + function getContextualTypeForArgument(callTarget, arg, contextFlags) { var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + function getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & 4 /* Completion */ && signature.target) { + var baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { @@ -52383,7 +52809,7 @@ var ts; } /* falls through */ case 196 /* NewExpression */: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case 198 /* TypeAssertionExpression */: case 216 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); @@ -52598,8 +53024,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -52700,7 +53126,7 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; } return literalType; } @@ -52837,7 +53263,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 1835008 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -52946,7 +53372,7 @@ 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 */ | 524288 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { result.objectFlags |= 16384 /* JSLiteral */; } @@ -53044,7 +53470,7 @@ var ts; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 1835008 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -53124,7 +53550,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 */ | 524288 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -53596,8 +54022,8 @@ var ts; function symbolHasNonMethodDeclaration(symbol) { return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } - function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */); @@ -53605,22 +54031,34 @@ var ts; function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + function reportObjectPossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + } + function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? - (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + reportError(node, kind); var t = getNonNullableType(type); return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) { @@ -53629,10 +54067,16 @@ var ts; return nonNullType; } function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + function checkPropertyAccessChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); } function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node) { while (node.parent.kind === 199 /* ParenthesizedExpression */) { @@ -53640,8 +54084,7 @@ var ts; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var _a = checkOptionalExpression(node, left), isOptional = _a.isOptional, leftType = _a.type; + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -53694,7 +54137,7 @@ var ts; } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { // Only compute control flow type if this is a property access expression that isn't an @@ -54016,7 +54459,15 @@ var ts; return false; } function checkIndexedAccess(node) { - var _a = checkOptionalExpression(node, node.expression), isOptional = _a.isOptional, exprType = _a.type; + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + function checkElementAccessChain(node) { + var exprType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -54032,7 +54483,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -54103,7 +54554,7 @@ var ts; // interface B extends A { (x: 'foo'): string } // const b: B; // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] - function reorderCandidates(signatures, result, isOptionalCall) { + function reorderCandidates(signatures, result, callChainFlags) { var lastParent; var lastSymbol; var cutoffIndex = 0; @@ -54133,7 +54584,7 @@ var ts; lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -54144,7 +54595,7 @@ var ts; else { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature); } } function isSpreadArgument(arg) { @@ -54228,7 +54679,7 @@ var ts; // the declared number of type parameters, the call has an incorrect arity. var numTypeParameters = ts.length(signature.typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - return !typeArguments || + return !ts.some(typeArguments) || (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. @@ -54439,7 +54890,19 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var thisArgumentType = void 0; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (ts.isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -54666,7 +55129,7 @@ var ts; 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.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_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 (min < argCount && argCount < max) { @@ -54722,7 +55185,7 @@ var ts; } return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } - function resolveCall(node, signatures, candidatesOutArray, checkMode, isOptionalCall, fallbackError) { + function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { var isTaggedTemplate = node.kind === 197 /* TaggedTemplateExpression */; var isDecorator = node.kind === 156 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -54737,7 +55200,7 @@ var ts; } var candidates = candidatesOutArray || []; // reorderCandidates fills up the candidates array directly - reorderCandidates(signatures, candidates, isOptionalCall); + reorderCandidates(signatures, candidates, callChainFlags); if (!candidates.length) { if (reportErrors) { diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); @@ -54899,7 +55362,7 @@ var ts; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) { @@ -54917,7 +55380,7 @@ var ts; var inferenceContext = void 0; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - if (typeArguments) { + if (ts.some(typeArguments)) { typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); if (!typeArgumentTypes) { candidateForTypeArgumentError = candidate; @@ -54992,34 +55455,34 @@ var ts; var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; var _loop_15 = function (i) { - var symbols = ts.mapDefined(candidates, function (_a) { - var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; - return hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : - i < parameters.length ? parameters[i] : undefined; - }); + var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined; }); ts.Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { _loop_15(i); } - var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); - var hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); + var flags = 0 /* None */; + if (restParameterSymbols.length !== 0) { var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1 /* HasRestParameter */; + } + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2 /* HasLiteralTypes */; } return createSignature(candidates[0].declaration, /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. thisParameter, parameters, /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), - /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, - /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + /*typePredicate*/ undefined, minArgumentCount, flags); } function getNumNonRestParameters(signature) { var numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); @@ -55095,12 +55558,24 @@ var ts; var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */); } } return resolveUntypedCall(node); } - var _b = checkOptionalExpression(node, node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined), isOptional = _b.isOptional, funcType = _b.type; + var callChainFlags; + var funcType = checkExpression(node.expression); + if (ts.isCallChain(node)) { + var nonOptionalType = getOptionalExpressionType(funcType, node.expression); + callChainFlags = nonOptionalType === funcType ? 0 /* None */ : + ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ : + 4 /* IsInnerCallChain */; + funcType = nonOptionalType; + } + else { + callChainFlags = 0 /* None */; + } + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -55166,7 +55641,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, isOptional); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags); } function isGenericFunctionReturningFunction(signature) { return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature))); @@ -55229,7 +55704,7 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */); } // If expressionType's apparent type is an object type with no construct signatures but // one or more call signatures, the expression is processed as a function call. A compile-time @@ -55237,7 +55712,7 @@ var ts; // operation is Any. It is an error to have a Void this type. var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); if (!noImplicitAny) { if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); @@ -55322,8 +55797,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var constituent = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var constituent = types_17[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -55414,7 +55889,7 @@ var ts; invocationError(node.tag, apparentType, 0 /* Call */); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); } /** * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. @@ -55467,7 +55942,7 @@ var ts; invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage); } function createSignatureForJSXIntrinsic(node, result) { var namespace = getJsxNamespaceAt(node); @@ -55482,9 +55957,7 @@ var ts; return createSignature(declaration, /*typeParameters*/ undefined, /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, - /*returnTypePredicate*/ undefined, 1, - /*hasRestparameter*/ false, - /*hasLiteralTypes*/ false); + /*returnTypePredicate*/ undefined, 1, 0 /* None */); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -55507,7 +55980,7 @@ var ts; error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); return resolveErrorCall(node); } - return resolveCall(node, signatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */); } /** * Sometimes, we have a decorator that could accept zero arguments, @@ -55517,7 +55990,7 @@ var ts; function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } @@ -55588,7 +56061,7 @@ var ts; return false; } function mergeJSSymbols(target, source) { - if (source && (ts.hasEntries(source.exports) || ts.hasEntries(source.members))) { + if (source) { var links = getSymbolLinks(source); if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) { var inferred = isTransientSymbol(target) ? target : cloneSymbol(target); @@ -55898,7 +56371,7 @@ var ts; return type; } function getParameterNameAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -55915,11 +56388,11 @@ var ts; return tryGetTypeAtPosition(signature, pos) || anyType; } function tryGetTypeAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // We want to return the value undefined for an out of bounds parameter position, // so we need to check bounds here before calling getIndexedAccessType (which // otherwise would return the type 'undefined'). @@ -55954,7 +56427,7 @@ var ts; } function getParameterCount(signature) { var length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -55963,7 +56436,7 @@ var ts; return length; } function getMinArgumentCount(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { var minLength = restType.target.minLength; @@ -55975,14 +56448,14 @@ var ts; return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } return false; } function getEffectiveRestType(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -55999,7 +56472,7 @@ var ts; return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, inferenceContext) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -56032,7 +56505,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } } - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56040,7 +56513,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56317,8 +56790,8 @@ var ts; var witnesses = getSwitchClauseTypeOfWitnesses(node); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_4 = getBaseConstraintOfType(operandType) || operandType; - return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + var type_3 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -56445,9 +56918,9 @@ var ts; return links.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + 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 |= 1048576 /* NonInferrableType */; + returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } return anyFunctionType; @@ -56676,8 +57149,7 @@ var ts; var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); var func = ts.getContainingFunction(node); - if (func && func.kind !== 161 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + if (func && func.kind !== 161 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -56778,8 +57250,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -57413,25 +57885,10 @@ var ts; } return [effectiveLeft, effectiveRight]; } - function isYieldExpressionInClass(node) { - var current = node; - var parent = node.parent; - while (parent) { - if (ts.isFunctionLike(parent) && current === parent.body) { - return false; - } - else if (ts.isClassLike(current)) { - return true; - } - current = parent; - parent = parent.parent; - } - return false; - } function checkYieldExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 8192 /* YieldContext */) || isYieldExpressionInClass(node)) { + if (!(node.flags & 8192 /* YieldContext */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -57767,6 +58224,18 @@ var ts; } } } + function getReturnTypeOfSingleNonGenericCallSignature(funcType) { + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) { + var funcType = checkExpression(expr.expression); + var nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType); + return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType); + } /** * Returns the type of an expression. Unlike checkExpression, this function is simply concerned * with computing the type and may not fully check all contained sub-expressions for errors. @@ -57778,10 +58247,10 @@ var ts; // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. if (ts.isCallExpression(expr) && expr.expression.kind !== 101 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { - var _a = checkOptionalExpression(expr, expr.expression), isOptional = _a.isOptional, funcType = _a.type; - var signature = getSingleCallSignature(funcType); - if (signature && !signature.typeParameters) { - return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); + var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : + getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression)); + if (type) { + return type; } } else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) { @@ -57831,7 +58300,7 @@ var ts; (node.parent.kind === 194 /* ElementAccessExpression */ && node.parent.expression === node) || ((node.kind === 75 /* Identifier */ || node.kind === 152 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || (node.parent.kind === 171 /* TypeQuery */ && node.parent.exprName === node)) || - (node.parent.kind === 261 /* ExportSpecifier */ && (compilerOptions.preserveConstEnums || node.flags & 8388608 /* Ambient */)); // We allow reexporting const enums + (node.parent.kind === 261 /* ExportSpecifier */); // We allow reexporting const enums if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -58035,7 +58504,7 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -59210,7 +59679,7 @@ var ts; return; } // Verify there is no local declaration that could collide with the promise constructor. - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); @@ -59267,7 +59736,7 @@ var ts; function markEntityNameOrEntityExpressionAsReference(typeName) { if (!typeName) return; - var rootName = getFirstIdentifier(typeName); + var rootName = ts.getFirstIdentifier(typeName); var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol @@ -59307,8 +59776,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var typeNode = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var typeNode = types_19[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -61083,10 +61552,7 @@ var ts; firstDefaultClause = clause; } else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -61107,6 +61573,9 @@ var ts; } } ts.forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -61629,11 +62098,13 @@ var ts; // same when the derived property is from an assignment continue; } - if (basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property; - } - else if (basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor; + var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */; + var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */; + if (overriddenInstanceProperty || overriddenInstanceAccessor) { + var errorMessage_1 = overriddenInstanceProperty ? + ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : + 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 { var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 158 /* PropertyDeclaration */ && !d.initializer; }); @@ -61649,24 +62120,22 @@ var ts; || !ts.isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { - var errorMessage_1 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; - error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType)); + var errorMessage_2 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType)); } } - // correct case - continue; } + // correct case + continue; } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { - // method is overridden with method -- correct case + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { + // method is overridden with method or property -- correct case continue; } - else if (derived.flags & 98304 /* Accessor */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & 98304 /* Accessor */) { @@ -62172,22 +62641,6 @@ var ts; break; } } - function getFirstIdentifier(node) { - switch (node.kind) { - case 75 /* Identifier */: - return node; - case 152 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 75 /* Identifier */); - return node; - case 193 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 75 /* Identifier */); - return node; - } - } function getFirstNonModuleExportsIdentifier(node) { switch (node.kind) { case 75 /* Identifier */: @@ -62317,7 +62770,7 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - var moduleName = getFirstIdentifier(node.moduleReference); + var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } @@ -62384,7 +62837,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -64690,10 +65143,10 @@ var ts; if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -65576,7 +66029,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -65646,6 +66099,14 @@ var ts; case 2 /* Next */: return "nextType"; } } + function signatureHasRestParameter(s) { + return !!(s.flags & 1 /* HasRestParameter */); + } + ts.signatureHasRestParameter = signatureHasRestParameter; + function signatureHasLiteralTypes(s) { + return !!(s.flags & 2 /* HasLiteralTypes */); + } + ts.signatureHasLiteralTypes = signatureHasLiteralTypes; })(ts || (ts = {})); var ts; (function (ts) { @@ -66579,7 +67040,9 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } // Because we are updating existed propertyAccess we want to inherit its emitFlags // instead of using the default from createPropertyAccess return node.expression !== expression @@ -66617,7 +67080,9 @@ var ts; } ts.createElementAccess = createElementAccess; function updateElementAccess(node, expression, argumentExpression) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -66651,7 +67116,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (ts.isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -67253,7 +67720,7 @@ var ts; var node = createSynthesizedNode(231 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -69779,7 +70246,7 @@ var ts; var conditionalPrecedence = ts.getOperatorPrecedence(209 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { return ts.createParen(condition); } return condition; @@ -70377,6 +70844,12 @@ var ts; * Gets the property name of a BindingOrAssignmentElement */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement); + ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element."); + return propertyName; + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { case 190 /* BindingElement */: // `a` in `let { a: b } = ...` @@ -70412,9 +70885,8 @@ var ts; ? target.expression : target; } - ts.Debug.fail("Invalid property name for binding element."); } - ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; function isStringOrNumericLiteral(node) { var kind = node.kind; return kind === 10 /* StringLiteral */ @@ -72433,7 +72905,8 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node)) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); @@ -72502,6 +72975,17 @@ var ts; } return false; } + function bindingOrAssignmentElementContainsNonLiteralComputedName(element) { + var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element); + if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) { + return true; + } + var target = ts.getTargetOfBindingOrAssignmentElement(element); + return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target); + } + function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) { + return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName); + } /** * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * @@ -72532,7 +73016,8 @@ var ts; }; if (ts.isVariableDeclaration(node)) { var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); - if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node))) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); @@ -73831,8 +74316,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { - var member = members_5[_i]; + for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { + var member = members_6[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -74222,8 +74707,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -74835,7 +75320,12 @@ var ts; * * @param node The module declaration node. */ - function shouldEmitModuleDeclaration(node) { + function shouldEmitModuleDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration); + if (!node) { + // If we can't find a parse tree node, assume the node is instantiated. + return true; + } return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } /** @@ -75654,7 +76144,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); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -77411,7 +77901,7 @@ var ts; } return ts.updateParen(node, expression); } - function visitNonOptionalPropertyAccessExpression(node, captureThisArg) { + function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg) { if (ts.isOptionalChain(node)) { // If `node` is an optional chain, then it is the outermost chain of an optional expression. return visitOptionalExpression(node, captureThisArg); @@ -77420,27 +77910,17 @@ var ts; ts.Debug.assertNotNode(expression, ts.isSyntheticReference); var thisArg; if (captureThisArg) { - // `a.b` -> { expression: `(_a = a).b`, thisArg: `_a` } - thisArg = ts.createTempVariable(hoistVariableDeclaration); - expression = ts.createParen(ts.createAssignment(thisArg, expression)); + if (shouldCaptureInTempVariable(expression)) { + thisArg = ts.createTempVariable(hoistVariableDeclaration); + expression = ts.createAssignment(thisArg, expression); + } + else { + thisArg = expression; + } } - expression = ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)); - return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression; - } - function visitNonOptionalElementAccessExpression(node, captureThisArg) { - if (ts.isOptionalChain(node)) { - // If `node` is an optional chain, then it is the outermost chain of an optional expression. - return visitOptionalExpression(node, captureThisArg); - } - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - ts.Debug.assertNotNode(expression, ts.isSyntheticReference); - var thisArg; - if (captureThisArg) { - // `a[b]` -> { expression: `(_a = a)[b]`, thisArg: `_a` } - thisArg = ts.createTempVariable(hoistVariableDeclaration); - expression = ts.createParen(ts.createAssignment(thisArg, expression)); - } - expression = ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); + expression = node.kind === 193 /* PropertyAccessExpression */ + ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) + : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression; } function visitNonOptionalCallExpression(node, captureThisArg) { @@ -77453,8 +77933,8 @@ var ts; function visitNonOptionalExpression(node, captureThisArg) { switch (node.kind) { case 199 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg); - case 193 /* PropertyAccessExpression */: return visitNonOptionalPropertyAccessExpression(node, captureThisArg); - case 194 /* ElementAccessExpression */: return visitNonOptionalElementAccessExpression(node, captureThisArg); + case 193 /* PropertyAccessExpression */: + case 194 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg); case 195 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } @@ -77462,31 +77942,36 @@ var ts; function visitOptionalExpression(node, captureThisArg) { var _a = flattenChain(node), expression = _a.expression, chain = _a.chain; var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0])); - var temp = ts.createTempVariable(hoistVariableDeclaration); var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined; var leftExpression = ts.isSyntheticReference(left) ? left.expression : left; - var rightExpression = temp; + var capturedLeft = leftExpression; + if (shouldCaptureInTempVariable(leftExpression)) { + capturedLeft = ts.createTempVariable(hoistVariableDeclaration); + leftExpression = ts.createAssignment(capturedLeft, leftExpression); + } + var rightExpression = capturedLeft; var thisArg; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { case 193 /* PropertyAccessExpression */: - if (i === chain.length - 1 && captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - rightExpression = ts.createParen(ts.createAssignment(thisArg, rightExpression)); - } - rightExpression = ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)); - break; case 194 /* ElementAccessExpression */: if (i === chain.length - 1 && captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - rightExpression = ts.createParen(ts.createAssignment(thisArg, rightExpression)); + if (shouldCaptureInTempVariable(rightExpression)) { + thisArg = ts.createTempVariable(hoistVariableDeclaration); + rightExpression = ts.createAssignment(thisArg, rightExpression); + } + else { + thisArg = rightExpression; + } } - rightExpression = ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); + rightExpression = segment.kind === 193 /* PropertyAccessExpression */ + ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) + : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; case 195 /* CallExpression */: if (i === 0 && leftThisArg) { - rightExpression = ts.createFunctionCall(rightExpression, leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); + rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 101 /* SuperKeyword */ ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } else { rightExpression = ts.createCall(rightExpression, @@ -77496,22 +77981,27 @@ var ts; } ts.setOriginalNode(rightExpression, segment); } - var target = ts.createConditional(ts.createLogicalOr(ts.createStrictEquality(ts.createAssignment(temp, leftExpression), ts.createNull()), ts.createStrictEquality(temp, ts.createVoidZero())), ts.createVoidZero(), rightExpression); + var target = ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createVoidZero(), rightExpression); return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target; } - function createNotNullCondition(node) { - return ts.createBinary(ts.createBinary(node, ts.createToken(37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(55 /* AmpersandAmpersandToken */), ts.createBinary(node, ts.createToken(37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero())); + function createNotNullCondition(left, right, invert) { + return ts.createBinary(ts.createBinary(left, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(invert ? 56 /* BarBarToken */ : 55 /* AmpersandAmpersandToken */), ts.createBinary(right, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero())); } function transformNullishCoalescingExpression(node) { - var expressions = []; var left = ts.visitNode(node.left, visitor, ts.isExpression); - if (!ts.isIdentifier(left)) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - expressions.push(ts.createAssignment(temp, left)); - left = temp; + var right = left; + if (shouldCaptureInTempVariable(left)) { + right = ts.createTempVariable(hoistVariableDeclaration); + left = ts.createAssignment(right, left); } - expressions.push(ts.createParen(ts.createConditional(createNotNullCondition(left), left, ts.visitNode(node.right, visitor, ts.isExpression)))); - return ts.inlineExpressions(expressions); + return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression)); + } + function shouldCaptureInTempVariable(expression) { + // don't capture identifiers and `this` in a temporary variable + // `super` cannot be captured as it's no real variable + return !ts.isIdentifier(expression) && + expression.kind !== 103 /* ThisKeyword */ && + expression.kind !== 101 /* SuperKeyword */; } } ts.transformESNext = transformESNext; @@ -87669,6 +88159,7 @@ var ts; var combinedStatements; if (ts.isSourceFileJS(currentSourceFile)) { combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); } else { @@ -89440,7 +89931,11 @@ var ts; bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) + return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) + emitSkipped = true; return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -92194,8 +92689,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_20 = types; _d < types_20.length; _d++) { - var directive = types_20[_d]; + for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { + var directive = types_21[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -94070,31 +94565,39 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (system.directoryExists(directoryPath)) { + if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } return false; } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - if (compilerHost.createDirectory) { - compilerHost.createDirectory(directoryPath); - } - else { - system.createDirectory(directoryPath); + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + // NOTE: If patchWriteFileEnsuringDirectory has been called, + // the system.writeFile will do its own directory creation and + // the ensureDirectoriesExist call will always be redundant. + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); } } } var outputFingerprints; - function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + function writeFileWorker(fileName, data, writeByteOrderMark) { + if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) { + system.writeFile(fileName, data, writeByteOrderMark); + return; + } if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = system.createHash(data); // TODO: GH#18217 - var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); + var mtimeBefore = system.getModifiedTime(fileName); if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -94106,32 +94609,13 @@ var ts; } } system.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, mtime: mtimeAfter }); } - function writeFile(fileName, data, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { - writeFileIfUpdated(fileName, data, writeByteOrderMark); - } - else { - system.writeFile(fileName, data, writeByteOrderMark); - } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -95853,9 +96337,16 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - if (fail) - fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + var canonicalFileName_1 = host.getCanonicalFileName(fileName); + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) { + if (fail) { + if (ts.hasJSFileExtension(canonicalFileName_1)) { + fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName); + } + else { + fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + } + } return undefined; } var sourceFile = getSourceFile(fileName); @@ -95869,7 +96360,7 @@ var ts; fail(ts.Diagnostics.File_0_not_found, fileName); } } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) { fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); } } @@ -95927,6 +96418,19 @@ var ts; function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) { if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(fileName); + // If preserveSymlinks is true, module resolution wont jump the symlink + // but the resolved real path may be the .d.ts from project reference + // Note:: Currently we try the real path only if the + // file is from node_modules to avoid having to run real path on all file paths + if (!source && + host.realpath && + options.preserveSymlinks && + ts.isDeclarationFileName(fileName) && + ts.stringContains(fileName, ts.nodeModulesPathPart)) { + var realPath = host.realpath(fileName); + if (realPath !== fileName) + source = getSourceOfProjectReferenceRedirect(realPath); + } if (source) { var file_1 = ts.isString(source) ? findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) : @@ -96457,9 +96961,6 @@ var ts; else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && ts.isIncrementalCompilation(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { @@ -97504,6 +98005,7 @@ var ts; ts.Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = ts.createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -98234,7 +98736,7 @@ var ts; } var state = { fileInfos: fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), @@ -98270,33 +98772,6 @@ var ts; } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; - function convertFromReusableCompilerOptions(options, toAbsolutePath) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - function convertFromReusableCompilerOptionValue(option, value, toAbsolutePath) { - if (option) { - if (option.type === "list") { - var values = value; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value); - } - } - return value; - } function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -99029,7 +99504,7 @@ var ts; function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { return { relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, - ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? + ending: ts.hasJSFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, }; @@ -99115,7 +99590,7 @@ var ts; var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } function numberOfDirectorySeparators(str) { @@ -99249,10 +99724,13 @@ var ts; // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); + var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { return undefined; + } // If the module was found in @types, get the actual Node package name var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); @@ -99477,7 +99955,7 @@ var ts; /** Parses config file using System interface */ function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; @@ -99501,7 +99979,7 @@ var ts; } ts.getErrorSummaryText = getErrorSummaryText; function listFiles(program, writeFileName) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { ts.forEach(program.getSourceFiles(), function (file) { writeFileName(file.fileName); }); @@ -99512,6 +99990,7 @@ var ts; * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -99520,13 +99999,17 @@ var ts; // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + if (!isListFilesOnly) { + ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + } } } // Emit and report any errors we ran into. - var emitResult = program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + var emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: ts.emptyArray } + : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics; ts.addRange(diagnostics, emitDiagnostics); ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); @@ -99629,19 +100112,13 @@ var ts; createHash: ts.maybeBind(host, host.createHash), readDirectory: ts.maybeBind(host, host.readDirectory), }; - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - if (host.createDirectory) - host.createDirectory(directoryPath); - } - } function writeFile(fileName, text, writeByteOrderMark, onError) { try { ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); + // NOTE: If patchWriteFileEnsuringDirectory has been called, + // the host.writeFile will do its own directory creation and + // the ensureDirectoriesExist call will always be redundant. + ts.writeFileEnsuringDirectories(fileName, text, writeByteOrderMark, function (path, data, writeByteOrderMark) { return host.writeFile(path, data, writeByteOrderMark); }, function (path) { return host.createDirectory(path); }, function (path) { return host.directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -101418,30 +101895,25 @@ var ts; setupInitialBuild(state, cancellationToken); var reportQueue = true; var successfulProjects = 0; - var errorProjects = 0; while (true) { var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; - } } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ts.ExitStatus.DiagnosticsPresent_OutputsGenerated : - ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : - ts.ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); }) + ? ts.ExitStatus.Success + : successfulProjects + ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated + : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); @@ -101449,7 +101921,7 @@ var ts; return ts.ExitStatus.InvalidProject_OutputsSkipped; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped; } var options = state.options, host = state.host; var filesToDelete = options.dry ? [] : undefined; @@ -103744,6 +104216,25 @@ var ts; return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); } ts.documentSpansEqual = documentSpansEqual; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + ts.forEachUnique = forEachUnique; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -104491,10 +104982,11 @@ var ts; } var dependencyKeys = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]; var stringContent = host.readFile(fileName); - var content = stringContent && tryParseJson(stringContent); - if (!content) { + if (!stringContent) return undefined; - } + var content = tryParseJson(stringContent); + if (!content) + return false; var info = {}; for (var _i = 0, dependencyKeys_1 = dependencyKeys; _i < dependencyKeys_1.length; _i++) { var key = dependencyKeys_1[_i]; @@ -105019,8 +105511,10 @@ var ts; }); return { spans: spans, endOfLineState: 0 /* None */ }; function pushClassification(start, end, type) { + var length = end - start; + ts.Debug.assert(length > 0, "Classification had non-positive length of " + length); spans.push(start); - spans.push(end - start); + spans.push(length); spans.push(type); } } @@ -105439,8 +105933,7 @@ var ts; return 25 /* bigintLiteral */; } else if (tokenKind === 10 /* StringLiteral */) { - // TODO: GH#18217 - return token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token && token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -105698,7 +106191,7 @@ var ts; var candidates = []; checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); var types = ts.flatMap(candidates, function (candidate) { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); @@ -106848,6 +107341,7 @@ var ts; var completionKind = 5 /* None */; var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; + // This also gets mutated in nested-functions after the return var symbols = []; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; @@ -106954,8 +107448,15 @@ var ts; var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -106972,8 +107473,15 @@ var ts; var type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -107275,7 +107783,7 @@ var ts; typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); } /** - * Gathers symbols that can be imported from other files, deduplicating along the way. Symbols can be “duplicates” + * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, * if and only if the the first can be imported (it may be excluded due to package.json filtering in @@ -107351,7 +107859,7 @@ var ts; // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -107465,7 +107973,16 @@ var ts; } if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) { if (contextToken.parent.kind === 266 /* JsxOpeningElement */) { - return true; + // Two possibilities: + // 1.
/**/ + // - contextToken: GreaterThanToken (before cursor) + // - location: JSXElement + // - different parents (JSXOpeningElement, JSXElement) + // 2. /**/> + // - contextToken: GreaterThanToken (before cursor) + // - location: GreaterThanToken (after cursor) + // - same parent (JSXOpeningElement) + return location.parent.kind !== 266 /* JsxOpeningElement */; } if (contextToken.parent.kind === 267 /* JsxClosingElement */ || contextToken.parent.kind === 265 /* JsxSelfClosingElement */) { return !!contextToken.parent.parent && contextToken.parent.parent.kind === 264 /* JsxElement */; @@ -107540,7 +108057,7 @@ var ts; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 192 /* ObjectLiteralExpression */) { - var typeForObject = typeChecker.getContextualType(objectLikeContainer); + var typeForObject = typeChecker.getContextualType(objectLikeContainer, 4 /* Completion */); if (!typeForObject) return 2 /* Fail */; isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); @@ -108117,6 +108634,8 @@ var ts; return isFunctionLikeBodyKeyword(kind) || kind === 129 /* DeclareKeyword */ || kind === 134 /* ModuleKeyword */ + || kind === 144 /* TypeKeyword */ + || kind === 135 /* NamespaceKeyword */ || ts.isTypeKeyword(kind) && kind !== 145 /* UndefinedKeyword */; case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); @@ -109926,7 +110445,7 @@ var ts; return undefined; } function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet) { - var moduleSourceFile = symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; + var moduleSourceFile = (symbol.flags & 1536 /* Module */) && symbol.declarations && ts.find(symbol.declarations, ts.isSourceFile); if (!moduleSourceFile) return undefined; var exportEquals = symbol.exports.get("export=" /* ExportEquals */); @@ -110651,8 +111170,10 @@ var ts; || exportSpecifier.name.originalKeywordKind === 83 /* DefaultKeyword */; var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); - var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); - searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + var exportInfo = FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker); + if (exportInfo) { + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { @@ -111863,7 +112384,7 @@ var ts; // The property length will have two declarations of property length coming // from Array - Array and Array var documentationComment = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var comment = _a[_i].comment; if (comment === undefined) @@ -111892,7 +112413,7 @@ var ts; function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); @@ -111929,24 +112450,6 @@ var ts; return comment === undefined ? s : s + " " + comment; } } - /** - * Iterates through 'array' by index and performs the callback on each element of array until the callback - * returns a truthy value, then returns that value. - * If no such value is found, the callback is applied to each element of array and undefined is returned. - */ - function forEachUnique(array, callback) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array.indexOf(array[i]) === i) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - } - } - return undefined; - } function getJSDocTagNameCompletions() { return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { @@ -112871,7 +113374,8 @@ var ts; } var declName = ts.getNameOfDeclaration(node); if (declName && ts.isPropertyName(declName)) { - return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 + var propertyName = ts.getPropertyNameForPropertyNameNode(declName); + return propertyName && ts.unescapeLeadingUnderscores(propertyName); } switch (node.kind) { case 200 /* FunctionExpression */: @@ -113641,6 +114145,9 @@ var ts; case 265 /* JsxSelfClosingElement */: case 266 /* JsxOpeningElement */: return spanForJSXAttributes(n.attributes); + case 210 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + return spanForTemplateLiteral(n); } function spanForJSXElement(node) { var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); @@ -113659,6 +114166,12 @@ var ts; } return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } + function spanForTemplateLiteral(node) { + if (node.kind === 14 /* NoSubstitutionTemplateLiteral */ && node.text.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); + } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 18 /* OpenBraceToken */; } // If the block has no leading keywords and is inside an array literal or call expression, @@ -115961,7 +116474,7 @@ var ts; // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration - var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + var locationIsSymbolDeclaration = symbol.declarations && ts.find(symbol.declarations, function (declaration) { return declaration === (location.kind === 128 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { @@ -116868,8 +117381,8 @@ var ts; rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */), // in other cases there should be no space between '?' and next token rule("NoSpaceAfterQuestionMark", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceBeforeDot", anyToken, [24 /* DotToken */, 28 /* QuestionDotToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceAfterDot", [24 /* DotToken */, 28 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBetweenImportParenInImportType", 95 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between @@ -119001,7 +119514,10 @@ var ts; if (ts.isCallOrNewExpression(parent)) { if (!parent.arguments) return false; - var currentNode = ts.Debug.assertDefined(ts.find(parent.arguments, function (arg) { return arg.pos === child.pos; })); + var currentNode = ts.find(parent.arguments, function (arg) { return arg.pos === child.pos; }); + // If it's not one of the arguments, don't look past this + if (!currentNode) + return false; var currentIndex = parent.arguments.indexOf(currentNode); if (currentIndex === 0) return false; // Can't look at previous node if first @@ -119420,6 +119936,18 @@ var ts; cb(tracker); return tracker.getChanges(); }; + ChangeTracker.prototype.pushRaw = function (sourceFile, change) { + ts.Debug.assertEqual(sourceFile.fileName, change.fileName); + for (var _i = 0, _a = change.textChanges; _i < _a.length; _i++) { + var c = _a[_i]; + this.changes.push({ + kind: ChangeKind.Text, + sourceFile: sourceFile, + text: c.newText, + range: ts.createTextRangeFromSpan(c.span), + }); + } + }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); }; @@ -119548,7 +120076,7 @@ var ts; endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); if (!endNode) { if (!ts.isArrowFunction(node)) - return; // Function missing parentheses, give up + return false; // Function missing parentheses, give up // If no `)`, is an arrow function `x => x`, so use the end of the first parameter endNode = ts.first(node.parameters); } @@ -119557,6 +120085,7 @@ var ts; endNode = node.kind !== 241 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + return true; }; ChangeTracker.prototype.tryInsertThisTypeAnnotation = function (sourceFile, node, type) { var start = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1; @@ -121183,20 +121712,20 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, formatContext, preferences); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, formatContext, preferences); }); }, }); @@ -121236,7 +121765,7 @@ var ts; } return errorCode; } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, formatContext, preferences) { if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 103 /* ThisKeyword */) { return undefined; } @@ -121247,7 +121776,7 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken, formatContext, preferences); return parent; } if (ts.isPropertyAccessExpression(parent)) { @@ -121264,7 +121793,7 @@ var ts; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken, formatContext, preferences); return symbol.valueDeclaration; } return undefined; @@ -121278,14 +121807,14 @@ var ts; // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken, formatContext, preferences); return param; } return undefined; @@ -121293,14 +121822,14 @@ var ts; case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host, formatContext, preferences); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } return undefined; @@ -121315,12 +121844,12 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken, formatContext, preferences) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host, formatContext, preferences); } } - function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken, formatContext, preferences) { if (!ts.isIdentifier(parameterDeclaration.name)) { return; } @@ -121336,7 +121865,7 @@ var ts; for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; if (declaration && !declaration.type && !declaration.initializer) { - annotate(changes, sourceFile, declaration, type, program, host); + annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences); } } if (needParens) @@ -121365,7 +121894,7 @@ var ts; ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)), ]); } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken, formatContext, preferences) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); @@ -121376,11 +121905,11 @@ var ts; annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); } else { - annotate(changes, sourceFile, param, type, program, host); + annotate(changes, sourceFile, param, type, program, host, formatContext, preferences); } } } - function annotate(changes, sourceFile, declaration, type, program, host) { + function annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (ts.isInJSFile(sourceFile) && declaration.kind !== 157 /* PropertySignature */) { @@ -121392,11 +121921,32 @@ var ts; var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); addJSDocTags(changes, sourceFile, parent, [typeTag]); } - else { + else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences)) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } } } + function tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences) { + var _a; + if (ts.isLiteralImportTypeNode(typeNode) && typeNode.qualifier && type.symbol) { + // Replace 'import("./a").SomeType' with 'SomeType' and an actual import if possible + var moduleSymbol = (_a = ts.find(type.symbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) === null || _a === void 0 ? void 0 : _a.getSourceFile().symbol; + // Symbol for the left-most thing after the dot + if (moduleSymbol) { + var symbol = ts.getFirstIdentifier(typeNode.qualifier).symbol; + var action = codefix.getImportCompletionAction(symbol, moduleSymbol, sourceFile, symbol.name, host, program, formatContext, declaration.pos, preferences); + if (action.codeAction.changes.length && changes.tryInsertTypeAnnotation(sourceFile, declaration, ts.createTypeReferenceNode(typeNode.qualifier, typeNode.typeArguments))) { + for (var _i = 0, _b = action.codeAction.changes; _i < _b.length; _i++) { + var change = _b[_i]; + var file = sourceFile.fileName === change.fileName ? sourceFile : ts.Debug.assertDefined(program.getSourceFile(change.fileName)); + changes.pushRaw(file, change); + } + return true; + } + } + } + return false; + } function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { var signature = parameterInferences.length && parameterInferences[0].declaration.parent; if (!signature) { @@ -122088,7 +122638,7 @@ var ts; } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); } function addCandidateType(usage, type) { if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { @@ -123895,6 +124445,7 @@ var ts; var filteredCount = 0; var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host); var allSourceFiles = program.getSourceFiles(); + var globalTypingsCache = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); forEachExternalModule(program.getTypeChecker(), allSourceFiles, function (module, sourceFile) { if (sourceFile === undefined) { if (!packageJson || packageJson.allowsImportingAmbientModule(module, allSourceFiles)) { @@ -123904,7 +124455,9 @@ var ts; filteredCount++; } } - else if (sourceFile && sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + else if (sourceFile && + sourceFile !== from && + isImportablePath(from.fileName, sourceFile.fileName, ts.hostGetCanonicalFileName(host), globalTypingsCache)) { if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile, allSourceFiles)) { cb(module); } @@ -123934,10 +124487,13 @@ var ts; * Don't include something from a `node_modules` that isn't actually reachable by a global import. * A relative import to node_modules is usually a bad idea. */ - function isImportablePath(fromPath, toPath) { + function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } function moduleSymbolToValidIdentifier(moduleSymbol, target) { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); @@ -123982,6 +124538,7 @@ var ts; readFile: ts.maybeBind(host, host.readFile), useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || program.getProbableSymlinks, + getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), }; var usesNodeCoreModules; return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; @@ -125557,14 +126114,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); - if (sig.hasRestParameter) { + if (ts.signatureHasRestParameter(sig)) { someSigHasRestParameter = true; } - if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!ts.signatureHasRestParameter(sig) || ts.signatureHasRestParameter(maxArgsSignature))) { maxArgsSignature = sig; } } - var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + var maxNonRestArgs = maxArgsSignature.parameters.length - (ts.signatureHasRestParameter(maxArgsSignature) ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { @@ -128049,7 +128606,7 @@ var ts; if (!selection || !ts.isTypeNode(selection)) return undefined; var checker = context.program.getTypeChecker(); - var firstStatement = ts.Debug.assertDefined(isJS ? ts.findAncestor(selection, isStatementAndHasJSDoc) : ts.findAncestor(selection, ts.isStatement), "Should find a statement"); + var firstStatement = ts.Debug.assertDefined(ts.findAncestor(selection, ts.isStatement), "Should find a statement"); var typeParameters = collectTypeParameters(checker, selection, firstStatement, file); if (!typeParameters) return undefined; @@ -128080,9 +128637,6 @@ var ts; } return undefined; } - function isStatementAndHasJSDoc(n) { - return ts.isStatement(n) && ts.hasJSDocNodes(n); - } function rangeContainsSkipTrivia(r1, node, file) { return ts.rangeContainsStartEnd(r1, ts.skipTrivia(file.text, node.pos), node.end); } @@ -130006,8 +130560,9 @@ var ts; return TypeObject; }()); var SignatureObject = /** @class */ (function () { - function SignatureObject(checker) { + function SignatureObject(checker, flags) { this.checker = checker; + this.flags = flags; } SignatureObject.prototype.getDeclaration = function () { return this.declaration; @@ -130045,13 +130600,12 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + ts.forEachUnique(declarations, function (declaration) { var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); - } + }); } return doc; } @@ -130362,9 +130916,7 @@ var ts; names.push(entry); } else { - if (entry.scriptKind !== 6 /* JSON */) { - names.push(entry.hostFileName); - } + names.push(entry.hostFileName); } }); return names; @@ -130932,12 +131484,11 @@ var ts; var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName, emitOnlyDtsFiles) { - if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + return ts.getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit); } // Signature help /** diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index b91087a1585..b01f079dc8b 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.7"; + const versionMajorMinor = "3.8"; /** The version of the TypeScript compiler release */ const version: string; } @@ -1964,6 +1964,8 @@ declare namespace ts { DiagnosticsPresent_OutputsSkipped = 1, DiagnosticsPresent_OutputsGenerated = 2, InvalidProject_OutputsSkipped = 3, + ProjectReferenceCycle_OutputsSkipped = 4, + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ProjectReferenceCycle_OutputsSkupped = 4 } export interface EmitResult { @@ -2376,6 +2378,7 @@ declare namespace ts { JSLiteral = 16384, FreshLiteral = 32768, ArrayLiteral = 65536, + ObjectRestType = 131072, ClassOrInterface = 3, } export interface ObjectType extends Type { @@ -3169,8 +3172,9 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + readonly importModuleSpecifierPreference?: "auto" | "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: boolean; @@ -3522,6 +3526,7 @@ declare namespace ts { function isCallExpression(node: Node): node is CallExpression; function isCallChain(node: Node): node is CallChain; function isOptionalChain(node: Node): node is PropertyAccessChain | ElementAccessChain | CallChain; + function isNullishCoalesce(node: Node): boolean; function isNewExpression(node: Node): node is NewExpression; function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression; function isTypeAssertion(node: Node): node is TypeAssertion; @@ -5071,7 +5076,7 @@ declare namespace ts { 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[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; dispose(): void; } @@ -5194,7 +5199,7 @@ declare namespace ts { } interface FileTextChanges { fileName: string; - textChanges: TextChange[]; + textChanges: readonly TextChange[]; isNewFile?: boolean; } interface CodeAction { diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index f8686be591c..23d6fd75d8d 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -76,67 +76,20 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +/* @internal */ var ts; (function (ts) { - // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. - // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.7"; - /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; -})(ts || (ts = {})); -(function (ts) { - /* @internal */ - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - ts.emptyArray = []; - /** Create a MapLike with good performance. */ - function createDictionaryObject() { - var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - return map; - } - /** Create a new map. If a template object is provided, the map will copy entries from it. */ - function createMap() { - return new ts.MapCtr(); - } - ts.createMap = createMap; - function createMapFromEntries(entries) { - var map = createMap(); - for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { - var _a = entries_1[_i], key = _a[0], value = _a[1]; - map.set(key, value); + function createMapShim() { + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; } - return map; - } - ts.createMapFromEntries = createMapFromEntries; - function createMapFromTemplate(template) { - var map = new ts.MapCtr(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in template) { - if (hasOwnProperty.call(template, key)) { - map.set(key, template[key]); - } - } - return map; - } - ts.createMapFromTemplate = createMapFromTemplate; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // eslint-disable-next-line no-in-operator - ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - // Keep the class inside a function so it doesn't get compiled if it's not used. - function shimMap() { var MapIterator = /** @class */ (function () { function MapIterator(currentEntry, selector) { this.currentEntry = currentEntry; @@ -272,7 +225,75 @@ var ts; return class_1; }()); } - ts.shimMap = shimMap; + ts.createMapShim = createMapShim; +})(ts || (ts = {})); +var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.8"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".0-dev"; +})(ts || (ts = {})); +(function (ts) { + /* @internal */ + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + /** + * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). + */ + function tryGetNativeMap() { + // Internet Explorer's Map doesn't support iteration, so don't use it. + // eslint-disable-next-line no-in-operator + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; + } + ts.tryGetNativeMap = tryGetNativeMap; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + ts.Map = ts.tryGetNativeMap() || (function () { + // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it. + if (typeof ts.createMapShim === "function") { + return ts.createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); + /** Create a new map. */ + function createMap() { + return new ts.Map(); + } + ts.createMap = createMap; + /** Create a new map from an array of entries. */ + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + /** Create a new map from a template object is provided, the map will copy entries from it. */ + function createMapFromTemplate(template) { + var map = new ts.Map(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; function length(array) { return array ? array.length : 0; } @@ -1854,20 +1875,6 @@ var ts; return str.indexOf(substring) !== -1; } ts.stringContains = stringContains; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -2181,11 +2188,14 @@ var ts; if (isFlags) { var result = ""; var remainingFlags = value; - for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { - var _a = members[i], enumValue = _a[0], enumName = _a[1]; - if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; + if (enumValue > value) { + break; + } + if (enumValue !== 0 && enumValue & value) { + result = "" + result + (result ? "|" : "") + enumName; remainingFlags &= ~enumValue; - result = "" + enumName + (result ? "|" : "") + result; } } if (remainingFlags === 0) { @@ -2193,8 +2203,8 @@ var ts; } } else { - for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { - var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + for (var _b = 0, members_2 = members; _b < members_2.length; _b++) { + var _c = members_2[_b], enumValue = _c[0], enumName = _c[1]; if (enumValue === value) { return enumName; } @@ -2268,6 +2278,33 @@ var ts; ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; var isDebugInfoEnabled = false; + var extendedDebugModule; + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + Debug.formatControlFlowGraph = formatControlFlowGraph; + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator + Object.defineProperties(flowNode, { + __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } }, + __debugToString: { value: function () { return formatControlFlowGraph(this); } } + }); + } + } + } + Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; /** * Injects debug information into frequently used types. */ @@ -2311,6 +2348,20 @@ var ts; }); } } + // attempt to load extended debugging information + try { + if (ts.sys && ts.sys.require) { + var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath())); + var result = ts.sys.require(basePath, "./compiler-debug"); + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch (_a) { + // do nothing + } isDebugInfoEnabled = true; } Debug.enableDebugInfo = enableDebugInfo; @@ -2474,8 +2525,6 @@ var ts; } /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - var args = typeof process === "undefined" ? [] : process.argv; - ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(args)); })(ts || (ts = {})); /* @internal */ var ts; @@ -3370,6 +3419,7 @@ var ts; /* @internal */ TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + // NOTE: Ensure this is up-to-date with src/debug/debug.ts var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -3425,6 +3475,8 @@ var ts; // When build skipped because passed in project is invalid ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped"; // When build is skipped because project references form cycle + ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ @@ -3434,6 +3486,14 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + /* @internal */ + var ContextFlags; + (function (ContextFlags) { + ContextFlags[ContextFlags["None"] = 0] = "None"; + ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; + ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; + ContextFlags[ContextFlags["Completion"] = 4] = "Completion"; + })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {})); // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { @@ -3836,19 +3896,20 @@ var ts; ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 131072] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 262144] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 524288] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 1048576] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 786432] = "RequiresWidening"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 1835008] = "PropagatingFlags"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -3875,6 +3936,20 @@ var ts; SignatureKind[SignatureKind["Call"] = 0] = "Call"; SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + /* @internal */ + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter"; + SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes"; + SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain"; + SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain"; + // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us + // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when + // instantiating the return type. + SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags"; + SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags"; + })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {})); var IndexKind; (function (IndexKind) { IndexKind[IndexKind["String"] = 0] = "String"; @@ -4875,16 +4950,6 @@ var ts; } } ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; - function recursiveCreateDirectory(directoryPath, sys) { - var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); - if (shouldCreateParent) { - recursiveCreateDirectory(basePath, sys); - } - if (shouldCreateParent || !sys.directoryExists(directoryPath)) { - sys.createDirectory(directoryPath); - } - } /** * patch writefile to create folder before writing the file */ @@ -4893,11 +4958,7 @@ var ts; // patch writefile to create folder before writing the file var originalWriteFile = sys.writeFile; sys.writeFile = function (path, data, writeBom) { - var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); - if (directoryPath && !sys.directoryExists(directoryPath)) { - recursiveCreateDirectory(directoryPath, sys); - } - originalWriteFile.call(sys, path, data, writeBom); + return ts.writeFileEnsuringDirectories(path, data, !!writeBom, function (path, data, writeByteOrderMark) { return originalWriteFile.call(sys, path, data, writeByteOrderMark); }, function (path) { return sys.createDirectory(path); }, function (path) { return sys.directoryExists(path); }); }; } ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory; @@ -5046,6 +5107,15 @@ var ts; bufferFrom: bufferFrom, base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + require: function (baseDir, moduleName) { + try { + var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath: modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error: error }; + } + } }; return nodeSystem; /** @@ -5184,6 +5254,7 @@ var ts; if (fsSupportsRecursive) { return watchDirectoryUsingFsWatch; } + // defer watchDirectoryRecursively as it depends on `ts.createMap()` which may not be usable yet. var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? createWatchDirectoryUsing(fsWatchFile) : tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? @@ -5628,6 +5699,673 @@ var ts; ts.Debug.isDebugging = true; } })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + //// Path Tests + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + //// Path Parsing + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArrays([root], rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + //// Path Formatting + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + //// Path Normalization + /** + * Normalize path separators, converting `\` into `/`. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + //// Path Comparisons + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * @deprecated Use `containsPath` if possible. + */ + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + //// Relative Paths + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArrays([""], relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; +})(ts || (ts = {})); // // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ @@ -5655,7 +6393,7 @@ var ts; An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), - An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), @@ -5863,7 +6601,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd_1323", "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5899,6 +6637,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"), 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), @@ -6026,7 +6765,6 @@ var ts; Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), @@ -6196,8 +6934,8 @@ var ts; JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2610, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_proper_2610", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member property."), - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2611, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_access_2611", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member accessor."), + _0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property: diag(2610, ts.DiagnosticCategory.Error, "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610", "'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property."), + _0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor: diag(2611, ts.DiagnosticCategory.Error, "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611", "'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor."), Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), @@ -6420,6 +7158,8 @@ var ts; Parameter_0_of_accessor_has_or_is_using_private_name_1: diag(4106, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106", "Parameter '{0}' of accessor has or is using private name '{1}'."), Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2: diag(4107, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107", "Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'."), Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4108, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108", "Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named."), + Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), + Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -6427,6 +7167,7 @@ var ts; Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Unknown_compiler_option_0_Did_you_mean_1: diag(5025, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"), Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), @@ -6457,6 +7198,7 @@ var ts; 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}'?"), 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."), @@ -6503,7 +7245,7 @@ var ts; Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has an unsupported extension. The only supported extensions are {1}."), Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), @@ -6711,6 +7453,8 @@ var ts; 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."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), + File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -6814,6 +7558,7 @@ var ts; Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), + Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"), Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), @@ -9046,7 +9791,7 @@ var ts; ts.getDeclarationOfKind = getDeclarationOfKind; /** Create a new escaped identifier map. */ function createUnderscoreEscapedMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; function hasEntries(map) { @@ -9102,13 +9847,6 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -9915,6 +10653,11 @@ var ts; break; case 201 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); + case 275 /* CaseClause */: + case 276 /* DefaultClause */: + var start = ts.skipTrivia(sourceFile.text, node.pos); + var end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return ts.createTextSpanFromBounds(start, end); } if (errorNode === undefined) { // If we don't have a better node, then just set the error on the first token of @@ -10727,7 +11470,7 @@ var ts; (node.typeArguments[0].kind === 142 /* StringKeyword */ || node.typeArguments[0].kind === 139 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 195 /* CallExpression */) { return false; } @@ -10739,7 +11482,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -10961,27 +11704,31 @@ var ts; isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true); } ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; - function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { - return isLiteralLikeElementAccess(node) - && ((!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */) || - isEntityNameExpression(node.expression) || - isBindableStaticElementAccessExpression(node.expression, /*excludeThisKeyword*/ true)); - } - ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression; + /** x.y OR x[0] */ function isLiteralLikeAccess(node) { return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node); } ts.isLiteralLikeAccess = isLiteralLikeAccess; + /** x[0] OR x['a'] OR x[Symbol.y] */ function isLiteralLikeElementAccess(node) { return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) || isWellKnownSymbolSyntactically(node.argumentExpression)); } ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; + /** Any series of property and element accesses. */ function isBindableStaticAccessExpression(node, excludeThisKeyword) { return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */ || isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; + /** Any series of property and element accesses, ending in a literal element access */ + function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { + return isLiteralLikeElementAccess(node) + && ((!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */) || + isEntityNameExpression(node.expression) || + isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true)); + } + ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression; function isBindableStaticNameExpression(node, excludeThisKeyword) { return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword); } @@ -11010,7 +11757,7 @@ var ts; if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) { return 0 /* None */; } - if (isBindableStaticNameExpression(expr.left.expression) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { // F.prototype = { ... } return 6 /* Prototype */; } @@ -11066,13 +11813,17 @@ var ts; nextToLast = nextToLast.expression; } var id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { - // exports.name = expr OR module.exports.name = expr + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + // ExportsProperty does not support binding with computed names + isBindableStaticAccessExpression(lhs)) { + // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return 1 /* ExportsProperty */; } - // F.G...x = expr - return 5 /* Property */; + if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs) && lhs.expression.kind !== 103 /* ThisKeyword */)) { + // F.G...x = expr + return 5 /* Property */; + } } return 0 /* None */; } @@ -12394,7 +13145,7 @@ var ts; */ function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); var extensionless = ts.removeFileExtension(relativePath); @@ -12477,6 +13228,25 @@ var ts; }, sourceFiles); } ts.writeFile = writeFile; + function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists); + createDirectory(directoryPath); + } + } + function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) { + // PERF: Checking for directory existence is expensive. Instead, assume the directory exists + // and fall back to creating it if the file write fails. + try { + writeFile(path, data, writeByteOrderMark); + } + catch (_a) { + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists); + writeFile(path, data, writeByteOrderMark); + } + } + ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories; function getLineOfLocalPosition(currentSourceFile, pos) { return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; } @@ -12916,6 +13686,23 @@ var ts; return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function getFirstIdentifier(node) { + switch (node.kind) { + case 75 /* Identifier */: + return node; + case 152 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 75 /* Identifier */); + return node; + case 193 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 75 /* Identifier */); + return node; + } + } + ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { return node.kind === 75 /* Identifier */ || node.kind === 103 /* ThisKeyword */ || node.kind === 193 /* PropertyAccessExpression */ && isDottedName(node.expression) || @@ -13434,20 +14221,6 @@ var ts; }); } ts.mutateMap = mutateMap; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); @@ -13474,7 +14247,7 @@ var ts; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { @@ -14539,11 +15312,47 @@ var ts; } ts.isCallChain = isCallChain; function isOptionalChain(node) { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + var kind = node.kind; + return !!(node.flags & 32 /* OptionalChain */) && + (kind === 193 /* PropertyAccessExpression */ + || kind === 194 /* ElementAccessExpression */ + || kind === 195 /* CallExpression */); } ts.isOptionalChain = isOptionalChain; + /* @internal */ + function isOptionalChainRoot(node) { + return isOptionalChain(node) && !!node.questionDotToken; + } + ts.isOptionalChainRoot = isOptionalChainRoot; + /** + * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`). + */ + /* @internal */ + function isExpressionOfOptionalChainRoot(node) { + return isOptionalChainRoot(node.parent) && node.parent.expression === node; + } + ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot; + /** + * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`: + * + * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`) + * 2. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain) + * 3. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is + * the end of the chain starting at `c?.`) + * 4. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is + * the end of the chain starting at `a?.`) + */ + /* @internal */ + function isOutermostOptionalChain(node) { + return !isOptionalChain(node.parent) // cases 1 and 2 + || isOptionalChainRoot(node.parent) // case 3 + || node !== node.parent.expression; // case 4 + } + ts.isOutermostOptionalChain = isOutermostOptionalChain; + function isNullishCoalesce(node) { + return node.kind === 208 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; + } + ts.isNullishCoalesce = isNullishCoalesce; function isNewExpression(node) { return node.kind === 196 /* NewExpression */; } @@ -15814,11 +16623,6 @@ var ts; return node.kind === 162 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; - /* @internal */ - function isOptionalChainRoot(node) { - return ts.isOptionalChain(node) && !!node.questionDotToken; - } - ts.isOptionalChainRoot = isOptionalChainRoot; /** True if has jsdoc nodes attached to it. */ /* @internal */ // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times @@ -15905,7 +16709,12 @@ var ts; this.checker = checker; } } - function Signature() { } + function Signature(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } function Node(kind, pos, end) { this.pos = pos; this.end = end; @@ -16180,273 +16989,6 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - /** - * Normalize path separators. - */ - function normalizeSlashes(path) { - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - function isVolumeCharacter(charCode) { - return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || - (charCode >= 65 /* A */ && charCode <= 90 /* Z */); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; - if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; - } - return -1; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - // POSIX or UNC - if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; // POSIX: "/" (or non-normalized "\") - var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; // UNC: "//server" or "\\server" - return p1 + 1; // UNC: "//server/" or "\\server\" - } - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) - return 2; // DOS: "c:" (but not "c:d") - } - // URL - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - // relative - return 0; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - // TODO(rbuckton): replace references with `resolvePath` - function normalizePath(path) { - return ts.resolvePath(path); - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - // If the path provided is itself the root, then return it. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = ts.removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - /** - * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArrays([root], rest); - } - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = ts.combinePaths(currentDirectory, path); - var rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - ts.getPathComponents = getPathComponents; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - */ - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var result = ts.createMap(); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { @@ -16463,15 +17005,15 @@ var ts; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { aParts.pop(); bParts.pop(); } - return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; } // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. @@ -16481,229 +17023,8 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); - var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArrays([""], relative, components); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - */ - function ensurePathIsNonModuleName(path) { - return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function getBaseFileName(path, extensions, ignoreCase) { - path = ts.normalizeSlashes(path); - // if the path provided is itself the root, then it has not file name. - var rootLength = ts.getRootLength(path); - if (rootLength === path.length) - return ""; - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - /** - * Combines paths. If a path is absolute, it replaces any previous path. - */ - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = ts.normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = ts.normalizeSlashes(relativePath); - if (!path || ts.getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. - */ - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - var combined = ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : ts.normalizeSlashes(path); - var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.resolvePath = resolvePath; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path) { - if (path.length === 0) - return false; - var ch = path.charCodeAt(path.length - 1); - return ch === 47 /* slash */ || ch === 92 /* backslash */; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - // check path for these segments: '', '.'. '..' - var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - var aRoot = a.substring(0, ts.getRootLength(a)); - var bRoot = b.substring(0, ts.getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0 /* EqualTo */) { - return result; - } - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); - var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_1 = componentComparer(aComponents[i], bComponents[i]); - if (result_1 !== 0 /* EqualTo */) { - return result_1; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - /** - * Performs a case-sensitive comparison of two paths. - */ - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); - var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function isDirectorySeparator(charCode) { - return charCode === 47 /* slash */ || charCode === 92 /* backslash */; - } function stripLeadingDirectorySeparator(s) { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); @@ -16722,10 +17043,6 @@ var ts; return "\\" + match; } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -16801,7 +17118,7 @@ var ts; } // getNormalizedPathComponents includes the separator for the root component. // We need to remove to create our regex correctly. - components[0] = removeTrailingDirectorySeparator(components[0]); + components[0] = ts.removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); } @@ -16863,7 +17180,7 @@ var ts; function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); + var absolutePath = ts.combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), @@ -16892,7 +17209,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -16902,8 +17219,8 @@ var ts; visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) @@ -16930,8 +17247,8 @@ var ts; } for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { visitDirectory(name, absoluteName, depth); @@ -16953,14 +17270,14 @@ var ts; var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") - var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include)); // Append the literal and canonical candidate base paths. includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -16977,9 +17294,9 @@ var ts; var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { // No "*" or "?" in the path - return !hasExtension(absolute) + return !ts.hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -17051,10 +17368,6 @@ var ts; return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJSFileExtension = hasJSFileExtension; - function hasJSOrJsonFileExtension(fileName) { - return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); - } - ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; function hasTSFileExtension(fileName) { return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -17144,14 +17457,9 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); @@ -17194,36 +17502,6 @@ var ts; return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") - extensions = [extensions]; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -18431,6 +18709,9 @@ var ts; function doInYieldAndAwaitContext(func) { return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func); } + function doOutsideOfYieldAndAwaitContext(func) { + return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func); + } function inContext(flags) { return (contextFlags & flags) !== 0; } @@ -22702,18 +22983,7 @@ var ts; node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); - // For instance properties specifically, since they are evaluated inside the constructor, - // we do *not * want to parse yield expressions, so we specifically turn the yield context - // off. The grammar would look something like this: - // - // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; - // - // The checker may still error in the static case to explicitly disallow the yield expression. - node.initializer = ts.hasModifier(node, 32 /* Static */) - ? allowInAnd(parseInitializer) - : doOutsideOfContext(8192 /* YieldContext */ | 4096 /* DisallowInContext */, parseInitializer); + node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer); parseSemicolon(); return finishNode(node); } @@ -23004,7 +23274,7 @@ var ts; parseExpected(87 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(18 /* OpenBraceToken */)) { - node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); }); parseExpected(19 /* CloseBraceToken */); } else { @@ -25066,6 +25336,15 @@ var ts; isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, // Basic { name: "target", @@ -25897,8 +26176,7 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { - var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; + function parseCommandLineWorker(getOptionNameMap, diagnostics, commandLine, readFile) { var options = {}; var fileNames = []; var errors = []; @@ -25925,7 +26203,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); + errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -25961,7 +26239,13 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); + var possibleOption = ts.getSpellingSuggestion(s, ts.optionDeclarations, function (opt) { return "--" + opt.name; }); + if (possibleOption) { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownDidYouMeanDiagnostic, s, possibleOption.name)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownOptionDiagnostic, s)); + } } } else { @@ -26004,11 +26288,13 @@ var ts; parseStrings(args); } } + var compilerOptionsDefaultDiagnostics = { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument + }; function parseCommandLine(commandLine, readFile) { - return parseCommandLineWorker(getOptionNameMap, [ - ts.Diagnostics.Unknown_compiler_option_0, - ts.Diagnostics.Compiler_option_0_expects_an_argument - ], commandLine, readFile); + return parseCommandLineWorker(getOptionNameMap, compilerOptionsDefaultDiagnostics, commandLine, readFile); } ts.parseCommandLine = parseCommandLine; /** @internal */ @@ -26033,10 +26319,11 @@ var ts; function parseBuildCommand(args) { var buildOptionNameMap; var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; - var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ - ts.Diagnostics.Unknown_build_option_0, - ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 - ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + }, args), options = _a.options, projects = _a.fileNames, errors = _a.errors; var buildOptions = options; if (projects.length === 0) { // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." @@ -26058,6 +26345,7 @@ var ts; return { buildOptions: buildOptions, projects: projects, errors: errors }; } ts.parseBuildCommand = parseBuildCommand; + /* @internal */ function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -26066,104 +26354,7 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - /* @internal */ - function printVersion() { - ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); - } - ts.printVersion = printVersion; - /* @internal */ - function printHelp(optionsList, syntaxPrefix) { - if (syntaxPrefix === void 0) { syntaxPrefix = ""; } - var output = []; - // We want to align our "syntax" and "examples" commands to a certain margin. - var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); - // Build up the syntactic skeleton. - var syntax = makePadding(marginLength - syntaxLength); - syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; - output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); - output.push(ts.sys.newLine + ts.sys.newLine); - // Build up the list of examples. - var padding = makePadding(marginLength); - output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); - output.push(padding + "tsc @args.txt" + ts.sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); - output.push(ts.sys.newLine); - output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); - // We want our descriptions to align at the same column in our output, - // so we keep track of the longest option usage string. - marginLength = 0; - var usageColumn = []; // Things like "-d, --declaration" go in here. - var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind - for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { - var option = optionsList_1[_i]; - // If an option lacks a description, - // it is not officially supported. - if (!option.description) { - continue; - } - var usageText_1 = " "; - if (option.shortName) { - usageText_1 += "-" + option.shortName; - usageText_1 += getParamType(option); - usageText_1 += ", "; - } - usageText_1 += "--" + option.name; - usageText_1 += getParamType(option); - usageColumn.push(usageText_1); - var description = void 0; - if (option.name === "lib") { - description = getDiagnosticText(option.description); - var element = option.element; - var typeMap = element.type; - optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); - } - else { - description = getDiagnosticText(option.description); - } - descriptionColumn.push(description); - // Set the new margin for the description column if necessary. - marginLength = Math.max(usageText_1.length, marginLength); - } - // Special case that can't fit in the loop. - var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; - var kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { - var kind = kindsList_1[_a]; - output.push(kind + " "); - } - output.push(ts.sys.newLine); - } - } - for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { - var line = output_1[_b]; - ts.sys.write(line); - } - return; - function getParamType(option) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - } - ts.printHelp = printHelp; + ts.getDiagnosticText = getDiagnosticText; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -26247,19 +26438,28 @@ var ts; name: "compilerOptions", type: "object", elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1 + }, }, { name: "typingOptions", type: "object", elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 + }, }, { name: "typeAcquisition", type: "object", elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 + } }, { name: "extends", @@ -26324,7 +26524,7 @@ var ts; function isRootOptionMap(knownOptions) { return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } - function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; @@ -26341,8 +26541,19 @@ var ts; var textOfKey = ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; - if (keyText && extraKeyDiagnosticMessage && !option) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + if (keyText && extraKeyDiagnostics && !option) { + if (knownOptions) { + var possibleOption = ts.getSpellingSuggestion(keyText, ts.arrayFrom(knownOptions.keys()), ts.identity); + if (possibleOption) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownDidYouMeanDiagnostic, keyText, possibleOption)); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } } var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { @@ -26426,8 +26637,8 @@ var ts; // vs what we set in the json // If need arises, we can modify this interface and callbacks as needed if (option) { - var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; - return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName); } else { return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, @@ -26482,7 +26693,7 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign(__assign({ compilerOptions: __assign(__assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; @@ -26503,12 +26714,12 @@ var ts; return undefined; return specs; } - function matchesSpecs(path, includeSpecs, excludeSpecs) { + function matchesSpecs(path, includeSpecs, excludeSpecs, host) { if (!includeSpecs) return function (_) { return true; }; - var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); - var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); - var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; @@ -26685,6 +26896,35 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + /* @internal */ + function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + var result = {}; + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name in options) { + if (ts.hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; + function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option) { + if (option.type === "list") { + var values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value); + } + } + return value; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -27073,7 +27313,7 @@ var ts; } function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); - convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, compilerOptionsDefaultDiagnostics, errors); if (configFileName) { options.configFilePath = ts.normalizeSlashes(configFileName); } @@ -27085,10 +27325,14 @@ var ts; function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); - convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + var diagnostics = { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1, + }; + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, diagnostics, errors); return options; } - function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnostics, errors) { if (!jsonOptions) { return; } @@ -27099,7 +27343,13 @@ var ts; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } else { - errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + var possibleOption = ts.getSpellingSuggestion(id, optionDeclarations, function (opt) { return opt.name; }); + if (possibleOption) { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownDidYouMeanDiagnostic, id, possibleOption.name)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownOptionDiagnostic, id)); + } } } } @@ -27135,7 +27385,7 @@ var ts; } function normalizeNonListOptionValue(option, basePath, value) { if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + value = ts.getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } @@ -28919,7 +29169,10 @@ var ts; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); - var flowNodeCreated = ts.identity; + function initFlowNode(node) { + ts.Debug.attachFlowNodeDebugInfo(node); + return node; + } var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -28948,6 +29201,7 @@ var ts; var currentReturnTarget; var currentTrueTarget; var currentFalseTarget; + var currentExceptionTarget; var preSwitchCaseFlow; var activeLabels; var hasExplicitReturn; @@ -28983,6 +29237,9 @@ var ts; symbolCount = 0; skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); + // Attach debugging information if necessary + ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); + ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -29005,6 +29262,7 @@ var ts; currentReturnTarget = undefined; currentTrueTarget = undefined; currentFalseTarget = undefined; + currentExceptionTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; emitFlags = 0 /* None */; @@ -29326,11 +29584,11 @@ var ts; blockScopeContainer.locals = undefined; } if (containerFlags & 4 /* IsControlFlowContainer */) { - var saveFlowNodeCreated = flowNodeCreated; var saveCurrentFlow = currentFlow; var saveBreakTarget = currentBreakTarget; var saveContinueTarget = currentContinueTarget; var saveReturnTarget = currentReturnTarget; + var saveExceptionTarget = currentExceptionTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && @@ -29338,7 +29596,7 @@ var ts; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isIIFE) { - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.node = node; } @@ -29346,11 +29604,11 @@ var ts; // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. currentReturnTarget = isIIFE || node.kind === 161 /* Constructor */ ? createBranchLabel() : undefined; + currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = ts.identity; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~2816 /* ReachabilityAndEmitFlags */; @@ -29376,9 +29634,9 @@ var ts; currentBreakTarget = saveBreakTarget; currentContinueTarget = saveContinueTarget; currentReturnTarget = saveReturnTarget; + currentExceptionTarget = saveExceptionTarget; activeLabels = saveActiveLabels; hasExplicitReturn = saveHasExplicitReturn; - flowNodeCreated = saveFlowNodeCreated; } else if (containerFlags & 64 /* IsInterface */) { seenThisKeyword = false; @@ -29519,9 +29777,6 @@ var ts; case 309 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; - case 307 /* JSDocClassTag */: - bindJSDocClassTag(node); - break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 288 /* SourceFile */: { bindEachFunctionsFirst(node.statements); @@ -29561,9 +29816,8 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 103 /* ThisKeyword */ || expr.kind === 101 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && - ts.isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + ts.isOptionalChain(expr); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -29620,10 +29874,10 @@ var ts; return isNarrowableReference(expr); } function createBranchLabel() { - return { flags: 4 /* BranchLabel */, antecedents: undefined }; + return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); } function createLoopLabel() { - return { flags: 8 /* LoopLabel */, antecedents: undefined }; + return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined }); } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag @@ -29642,36 +29896,32 @@ var ts; if (!expression) { return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - if (!ts.isOptionalChainRoot(expression.parent)) { - return unreachableFlow; - } + if ((expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) && + !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) { + return unreachableFlow; } if (!isNarrowingExpression(expression)) { return antecedent; } setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: flags, antecedent: antecedent, node: expression }); + return initFlowNode({ flags: flags, antecedent: antecedent, node: expression }); } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { - return antecedent; - } setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd }); + return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd }); } - function createFlowAssignment(antecedent, node) { + function createFlowMutation(flags, antecedent, node) { setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 16 /* Assignment */, antecedent: antecedent, node: node }); + var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node }); + if (currentExceptionTarget) { + addAntecedent(currentExceptionTarget, result); + } + return result; } function createFlowCall(antecedent, node) { setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 512 /* Call */, antecedent: antecedent, node: node }); - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }); + return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node }); } function finishFlowLabel(flow) { var antecedents = flow.antecedents; @@ -29731,7 +29981,7 @@ var ts; } function bindCondition(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); - if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && isOutermostOptionalChain(node))) { + if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -29862,87 +30112,56 @@ var ts; } function bindTryStatement(node) { var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - var tryPriors = []; - var oldFlowNodeCreated = flowNodeCreated; - // We hook the creation of all flow nodes within the `try` scope and store them so we can add _all_ of them - // as possible antecedents of the start of the `catch` or `finally` blocks. - // Don't bother intercepting the call if there's no finally or catch block that needs the information - if (node.catchClause || node.finallyBlock) { - flowNodeCreated = function (node) { return (tryPriors.push(node), node); }; - } + // We conservatively assume that *any* code in the try block can cause an exception, but we only need + // to track code that causes mutations (because only mutations widen the possible control flow type of + // a variable). The currentExceptionTarget is the target label for control flows that result from + // exceptions. We add all mutation flow nodes as antecedents of this label such that we can analyze them + // as possible antecedents of the start of catch or finally blocks. Furthermore, we add the current + // control flow to represent exceptions that occur before any mutations. + var saveExceptionTarget = currentExceptionTarget; + currentExceptionTarget = createBranchLabel(); + addAntecedent(currentExceptionTarget, currentFlow); bind(node.tryBlock); - flowNodeCreated = oldFlowNodeCreated; addAntecedent(preFinallyLabel, currentFlow); var flowAfterTry = currentFlow; var flowAfterCatch = unreachableFlow; if (node.catchClause) { - currentFlow = preTryFlow; - if (tryPriors.length) { - var preCatchFlow = createBranchLabel(); - addAntecedent(preCatchFlow, currentFlow); - for (var _i = 0, tryPriors_1 = tryPriors; _i < tryPriors_1.length; _i++) { - var p = tryPriors_1[_i]; - addAntecedent(preCatchFlow, p); - } - currentFlow = finishFlowLabel(preCatchFlow); - } + // Start of catch clause is the target of exceptions from try block. + currentFlow = finishFlowLabel(currentExceptionTarget); + // The currentExceptionTarget now represents control flows from exceptions in the catch clause. + // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block + // acts like a second try block. + currentExceptionTarget = createBranchLabel(); + addAntecedent(currentExceptionTarget, currentFlow); bind(node.catchClause); addAntecedent(preFinallyLabel, currentFlow); flowAfterCatch = currentFlow; } + var exceptionTarget = finishFlowLabel(currentExceptionTarget); + currentExceptionTarget = saveExceptionTarget; if (node.finallyBlock) { - // We add the nodes within the `try` block to the `finally`'s antecedents if there's no catch block - // (If there is a `catch` block, it will have all these antecedents instead, and the `finally` will - // have the end of the `try` block and the end of the `catch` block) - var preFinallyPrior = preTryFlow; - if (!node.catchClause) { - if (tryPriors.length) { - var preFinallyFlow_1 = createBranchLabel(); - addAntecedent(preFinallyFlow_1, preTryFlow); - for (var _a = 0, tryPriors_2 = tryPriors; _a < tryPriors_2.length; _a++) { - var p = tryPriors_2[_a]; - addAntecedent(preFinallyFlow_1, p); - } - preFinallyPrior = finishFlowLabel(preFinallyFlow_1); - } - } - // in finally flow is combined from pre-try/flow from try/flow from catch - // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable - // also for finally blocks we inject two extra edges into the flow graph. - // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it - // second -> edge that represents post-finally flow. - // these edges are used in following scenario: - // let a; (1) - // try { a = someOperation(); (2)} - // finally { (3) console.log(a) } (4) - // (5) a - // flow graph for this case looks roughly like this (arrows show ): - // (1-pre-try-flow) <--.. <-- (2-post-try-flow) - // ^ ^ - // |*****(3-pre-finally-label) -----| - // ^ - // |-- ... <-- (4-post-finally-label) <--- (5) - // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account - // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) - // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable - // Simply speaking code inside finally block is treated as reachable as pre-try-flow - // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. - // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from - // final flows of these blocks without taking pre-try flow into account. - // - // extra edges that we inject allows to control this behavior - // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }; + // Possible ways control can reach the finally block: + // 1) Normal completion of try block of a try-finally or try-catch-finally + // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally + // 3) Exception in try block of a try-finally + // 4) Exception in catch block of a try-catch-finally + // When analyzing a control flow graph that starts inside a finally block we want to consider all + // four possibilities above. However, when analyzing a control flow graph that starts outside (past) + // the finally block, we only want to consider the first two (if we're past a finally block then it + // must have completed normally). To make this possible, we inject two extra nodes into the control + // flow graph: An after-finally with an antecedent of the control flow at the end of the finally + // block, and a pre-finally with an antecedent that represents all exceptional control flows. The + // 'lock' property of the pre-finally references the after-finally, and the after-finally has a + // boolean 'locked' property that we set to true when analyzing a control flow that contained the + // the after-finally node. When the lock associated with a pre-finally is locked, the antecedent of + // the pre-finally (i.e. the exceptional control flows) are skipped. + var preFinallyFlow = initFlowNode({ flags: 4096 /* PreFinally */, antecedent: exceptionTarget, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); - // if flow after finally is unreachable - keep it - // otherwise check if flows after try and after catch are unreachable - // if yes - convert current flow to unreachable - // i.e. - // try { return "1" } finally { console.log(1); } - // console.log(2); // this line should be unreachable even if flow falls out of finally block + // If the end of the finally block is reachable, but the end of the try and catch blocks are not, + // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should + // result in an unreachable current control flow. if (!(currentFlow.flags & 1 /* Unreachable */)) { if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow @@ -29951,7 +30170,7 @@ var ts; } } if (!(currentFlow.flags & 1 /* Unreachable */)) { - var afterFinallyFlow = flowNodeCreated({ flags: 8192 /* AfterFinally */, antecedent: currentFlow }); + var afterFinallyFlow = initFlowNode({ flags: 8192 /* AfterFinally */, antecedent: currentFlow }); preFinallyFlow.lock = afterFinallyFlow; currentFlow = afterFinallyFlow; } @@ -29985,6 +30204,7 @@ var ts; var savedSubtreeTransformFlags = subtreeTransformFlags; subtreeTransformFlags = 0; var clauses = node.clauses; + var isNarrowingSwitch = isNarrowingExpression(node.parent.expression); var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { var clauseStart = i; @@ -29993,14 +30213,14 @@ var ts; i++; } var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; @@ -30064,7 +30284,7 @@ var ts; } function bindAssignmentTargetFlow(node) { if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); + currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } else if (node.kind === 191 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { @@ -30145,7 +30365,7 @@ var ts; if (operator === 62 /* EqualsToken */ && node.left.kind === 194 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } } @@ -30181,7 +30401,7 @@ var ts; } } else { - currentFlow = createFlowAssignment(currentFlow, node); + currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } } function bindVariableDeclarationFlow(node) { @@ -30203,12 +30423,9 @@ var ts; addDeclarationToSymbol(host.symbol, host, 32 /* Class */); } } - function isOutermostOptionalChain(node) { - return !ts.isOptionalChain(node.parent) || ts.isOptionalChainRoot(node.parent) || node !== node.parent.expression; - } function bindOptionalExpression(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); - if (!ts.isOptionalChain(node) || isOutermostOptionalChain(node)) { + if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -30246,7 +30463,7 @@ var ts; currentFlow = finishFlowLabel(preChainLabel); } doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget); - if (isOutermostOptionalChain(node)) { + if (ts.isOutermostOptionalChain(node)) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -30290,7 +30507,7 @@ var ts; if (node.expression.kind === 193 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } } @@ -30590,7 +30807,7 @@ var ts; var host = ts.getJSDocHost(typeAlias); container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); var declName = ts.getNameOfDeclaration(typeAlias); @@ -30603,7 +30820,12 @@ var ts; switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: - container = file; + if (!ts.isExternalOrCommonJsModule(file)) { + container = undefined; + } + else { + container = file; + } break; case 4 /* ThisProperty */: container = declName.parent.expression; @@ -30617,7 +30839,9 @@ var ts; case 0 /* None */: return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration"); } - declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + if (container) { + declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + } container = oldContainer; } } @@ -31013,6 +31237,8 @@ var ts; case 302 /* JSDocTypeLiteral */: case 185 /* MappedType */: return bindAnonymousTypeWorker(node); + case 307 /* JSDocClassTag */: + return bindJSDocClassTag(node); case 192 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); case 200 /* FunctionExpression */: @@ -31232,7 +31458,8 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -31248,7 +31475,7 @@ var ts; constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); } } - if (constructorSymbol) { + if (constructorSymbol && constructorSymbol.valueDeclaration) { // Declare a 'member' if the container is an ES5 class or ES6 constructor constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); // It's acceptable for multiple 'this' assignments of the same identifier to occur @@ -31321,6 +31548,10 @@ var ts; } function bindObjectDefinePrototypeProperty(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol) { + // Ensure the namespace symbol becomes class-like + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** @@ -31395,7 +31626,7 @@ var ts; } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); } return namespaceSymbol; @@ -32044,7 +32275,8 @@ var ts; || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type - || !node.body) { + || !node.body + || node.questionToken) { transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax @@ -32081,7 +32313,7 @@ var ts; function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 1048576 /* ContainsClassFields */; // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax. - if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type) { + if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken) { transformFlags |= 1 /* AssertTypeScript */; } // Hoisted variables related to class properties should live within the TypeScript class wrapper. @@ -32886,6 +33118,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 7] = "ResolvedTypeArguments"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -32896,12 +33129,6 @@ var ts; CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; })(CheckMode || (CheckMode = {})); - var ContextFlags; - (function (ContextFlags) { - ContextFlags[ContextFlags["None"] = 0] = "None"; - ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; - ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; - })(ContextFlags || (ContextFlags = {})); var AccessFlags; (function (AccessFlags) { AccessFlags[AccessFlags["None"] = 0] = "None"; @@ -33035,14 +33262,12 @@ var ts; undefinedSymbol.declarations = []; var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); globalThisSymbol.exports = globals; + globalThisSymbol.declarations = []; globals.set(globalThisSymbol.escapedName, globalThisSymbol); var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; - // This object is reused for `checkOptionalExpression` return values to avoid frequent GC due to nursery object allocations. - // This object represents a pool-size of 1. - var pooledOptionalTypeResult = { isOptional: false, type: undefined }; // for public members that accept a Node or one of its subtypes, we must guard against // synthetic nodes created during transformations by calling `getParseTreeNode`. // for most of these, we perform the guard only on `checker` to avoid any possible @@ -33161,9 +33386,9 @@ var ts; }, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (nodeIn) { + getContextualType: function (nodeIn, contextFlags) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); @@ -33212,7 +33437,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments), getAmbientModules: getAmbientModules, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { @@ -33341,10 +33566,10 @@ var ts; var errorType = createIntrinsicType(1 /* Any */, "error"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 262144 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 262144 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -33370,7 +33595,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", 1048576 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -33388,7 +33613,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 |= 1048576 /* NonInferrableType */; + anyFunctionType.objectFlags |= 2097152 /* 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); @@ -33397,10 +33622,10 @@ var ts; markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances var noIterationTypes = { @@ -33553,7 +33778,7 @@ var ts; var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } } } @@ -33563,7 +33788,7 @@ var ts; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -35041,7 +35266,7 @@ var ts; var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0); var symbol; if (name.kind === 75 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { @@ -35153,7 +35378,12 @@ var ts; return undefined; } var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl); - return init && getSymbolOfNode(init) || undefined; + if (init) { + var initSymbol = getSymbolOfNode(init); + if (initSymbol) { + return mergeJSSymbols(initSymbol, symbol); + } + } } function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); @@ -35580,8 +35810,8 @@ var ts; } function findConstructorDeclaration(node) { var members = node.members; - for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { - var member = members_2[_i]; + for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { + var member = members_3[_i]; if (member.kind === 161 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } @@ -36004,7 +36234,7 @@ var ts; // Type Reference or TypeAlias entity = Identifier meaning = 788968 /* Type */; } - var firstIdentifier = getFirstIdentifier(entityName); + var firstIdentifier = ts.getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { @@ -36496,8 +36726,6 @@ var ts; else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && ts.isClassLike(type.symbol.valueDeclaration) && - // Use `import` types for refs to other scopes, only anonymize something defined in the same scope - ts.findAncestor(type.symbol.valueDeclaration, function (d) { return d === ts.getSourceFileOfNode(context.enclosingDeclaration); }) && !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } @@ -36658,9 +36886,9 @@ var ts; } } } - var propertyName = symbolToName(propertySymbol, context, 111551 /* Value */, /*expectsIdentifier*/ true); - context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; + var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */); @@ -36859,7 +37087,7 @@ var ts; if (!context.tracker.trackSymbol) return; // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(accessExpression); + var firstIdentifier = ts.getFirstIdentifier(accessExpression); var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */); @@ -37225,22 +37453,34 @@ var ts; } } } + function isSingleQuotedStringNamed(d) { + var name = ts.getNameOfDeclaration(d); + if (name && ts.isStringLiteral(name) && (name.singleQuote || + (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")))) { + return true; + } + return false; + } function getPropertyNameNodeForSymbol(symbol, context) { - var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context); + var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed); + var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote); if (fromNameType) { return fromNameType; } + if (ts.isKnownSymbol(symbol)) { + return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3))); + } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); - return createPropertyNameNodeForIdentifierOrLiteral(rawName); + return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote); } // See getNameForSymbolFromNameType for a stringy equivalent - function getPropertyNameNodeForSymbolFromNameType(symbol, context) { + function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) { var nameType = symbol.nameType; if (nameType) { if (nameType.flags & 384 /* StringOrNumberLiteral */) { var name = "" + nameType.value; if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { - return ts.createLiteral(name); + return ts.createLiteral(name, !!singleQuote); } if (isNumericLiteralName(name) && ts.startsWith(name, "-")) { return ts.createComputedPropertyName(ts.createLiteral(+name)); @@ -37252,8 +37492,8 @@ var ts; } } } - function createPropertyNameNodeForIdentifierOrLiteral(name) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name); + function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -37293,7 +37533,7 @@ var ts; var visitedSymbols = ts.createMap(); var deferredPrivates; var oldcontext = context; - context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.mapMap(symbolTable, function (_symbol, name) { return [ts.unescapeLeadingUnderscores(name), true]; }), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { + context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it @@ -37311,6 +37551,10 @@ var ts; context.usedSymbolNames.set(name, true); }); } + ts.forEachEntry(symbolTable, function (symbol, name) { + var baseName = ts.unescapeLeadingUnderscores(name); + void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames` + }); var addingDeclare = !bundled; var exportEquals = symbolTable.get("export=" /* ExportEquals */); if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) { @@ -37502,7 +37746,11 @@ var ts; isPrivate = true; } var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0); - if (symbol.flags & 16 /* Function */) { + var isConstMergedWithNS = symbol.flags & 1536 /* Module */ && + symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && + symbol.escapedName !== "export=" /* ExportEquals */; + var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol); + if (symbol.flags & 16 /* Function */ || isConstMergedWithNSPrintableAsSignatureMerge) { serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } if (symbol.flags & 524288 /* TypeAlias */) { @@ -37513,7 +37761,8 @@ var ts; if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) - && !(symbol.flags & 32 /* Class */)) { + && !(symbol.flags & 32 /* Class */) + && !isConstMergedWithNSPrintableAsSignatureMerge) { serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags); } if (symbol.flags & 384 /* Enum */) { @@ -37530,7 +37779,7 @@ var ts; serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } } - if (symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */)) { + if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) { serializeModule(symbol, symbolName, modifierFlags); } if (symbol.flags & 64 /* Interface */) { @@ -37558,7 +37807,10 @@ var ts; } } function includePrivateSymbol(symbol) { + if (ts.some(symbol.declarations, ts.isParameterDeclaration)) + return; ts.Debug.assertDefined(deferredPrivates); + getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol deferredPrivates.set("" + getSymbolId(symbol), symbol); } function isExportingScope(enclosingDeclaration) { @@ -37617,8 +37869,14 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } + function getNamespaceMembersForSerialization(symbol) { + return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + } + function isTypeOnlyNamespace(symbol) { + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); }); + } function serializeModule(symbol, symbolName, modifierFlags) { - var members = !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + var members = getNamespaceMembersForSerialization(symbol); // Split NS members up by declaration - members whose parent symbol is the ns symbol vs those whose is not (but were added in later via merging) var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; }); var realMembers = locationMap.get("real") || ts.emptyArray; @@ -37628,17 +37886,20 @@ var ts; // so we don't even have placeholders to fill in. if (ts.length(realMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, /*suppressNewPrivateContext*/ false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); } if (ts.length(mergedMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - ts.forEach(mergedMembers, includePrivateSymbol); var nsBody = ts.createModuleBlock([ts.createExportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); - return ts.createExportSpecifier(name === localName ? undefined : localName, name); + var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); + includePrivateSymbol(target || s); + var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; + return ts.createExportSpecifier(name === targetName ? undefined : targetName, name); })))]); addResult(ts.createModuleDeclaration( /*decorators*/ undefined, @@ -37839,7 +38100,11 @@ var ts; case 254 /* ImportClause */: addResult(ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), + // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned + // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag + // In such cases, the `target` refers to the module itself already + ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 255 /* NamespaceImport */: addResult(ts.createImportDeclaration( @@ -37851,7 +38116,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([ ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName)) - ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 261 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, @@ -37865,6 +38130,7 @@ var ts; serializeMaybeAliasAssignment(symbol); break; case 208 /* BinaryExpression */: + case 193 /* PropertyAccessExpression */: // Could be best encoded as though an export specifier or as though an export assignment // If name is default or export=, do an export assignment // Otherwise do an export specifier @@ -37875,10 +38141,6 @@ var ts; serializeExportSpecifier(localName, targetName); } break; - case 193 /* PropertyAccessExpression */: - // A PAE alias is _always_ going to exist as an append to a top-level export, where our top level - // handling should always be sufficient to encode the export action itself - break; default: return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!"); } @@ -37902,7 +38164,8 @@ var ts; var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol); // serialize what the alias points to, preserve the declaration's initializer var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); - if (target) { + // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const + if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) { // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it // eg, `namespace A { export class B {} }; exports = A.B;` // Technically, this is all that's required in the case where the assignment is an entity name expression @@ -37977,6 +38240,7 @@ var ts; return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) && !getIndexInfoOfType(typeToSerialize, 0 /* String */) && !getIndexInfoOfType(typeToSerialize, 1 /* Number */) && + !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK !getDeclarationWithTypeAnnotation(hostSymbol) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && @@ -38120,7 +38384,7 @@ var ts; return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = getFirstIdentifier(node); + var leftmost = ts.getFirstIdentifier(node); var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); if (sym) { includePrivateSymbol(sym); @@ -38250,11 +38514,8 @@ var ts; return context.remappedSymbolNames.get("" + getSymbolId(symbol)); } } - if (input === "default" /* Default */) { - input = "_default"; - } - else if (input === "export=" /* ExportEquals */) { - input = "_exports"; + if (symbol) { + input = getNameCandidateWorker(symbol, input); } var i = 0; var original = input; @@ -38268,17 +38529,28 @@ var ts; } return input; } - function getInternalSymbolName(symbol, localName) { - if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) { - return context.remappedSymbolNames.get("" + getSymbolId(symbol)); - } + function getNameCandidateWorker(symbol, localName) { if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) { var flags = context.flags; context.flags |= 16777216 /* InInitialEntityName */; var nameCandidate = getNameOfSymbolAsWritten(symbol, context); context.flags = flags; - localName = ts.isIdentifierText(nameCandidate, languageVersion) && !ts.isStringANonContextualKeyword(nameCandidate) ? nameCandidate : getUnusedName("_default", symbol); + localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate; } + if (localName === "default" /* Default */) { + localName = "_default"; + } + else if (localName === "export=" /* ExportEquals */) { + localName = "_exports"; + } + localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_"); + return localName; + } + function getInternalSymbolName(symbol, localName) { + if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) { + return context.remappedSymbolNames.get("" + getSymbolId(symbol)); + } + localName = getNameCandidateWorker(symbol, localName); // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up context.remappedSymbolNames.set("" + getSymbolId(symbol), localName); return localName; @@ -38543,7 +38815,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); + var firstIdentifier = ts.getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); var id = importSymbol && "" + getSymbolId(importSymbol); if (importSymbol && !visited.has(id)) { @@ -38607,6 +38879,8 @@ var ts; return !!target.immediateBaseConstraint; case 6 /* JSDocTypeReference */: return !!getSymbolLinks(target).resolvedJSDocType; + case 7 /* ResolvedTypeArguments */: + return !!target.resolvedTypeArguments; } return ts.Debug.assertNever(propertyName); } @@ -38692,7 +38966,9 @@ var ts; } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); - return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + result.objectFlags |= 131072 /* ObjectRestType */; + return result; } // Determine the control flow type associated with a destructuring declaration or assignment. The following // forms of destructuring are possible: @@ -39078,23 +39354,23 @@ var ts; kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); - var members_3 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_3); + var members_4 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_3.has(name)) { + if (members_4.has(name)) { var exportedMember = exportedType_1.members.get(name); var union = createSymbol(s.flags | exportedMember.flags, name); union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_3.set(name, union); + members_4.set(name, union); } else { - members_3.set(name, s); + members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag return result; } @@ -39154,7 +39430,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -39294,16 +39570,12 @@ var ts; if (!declaration.statements.length) { return emptyObjectType; } - var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); - if (type_1.flags & 524288 /* Object */) { - return getRegularTypeOfObjectLiteral(type_1); - } - return type_1; + return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression))); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39371,7 +39643,7 @@ var ts; } if (!popTypeResolution()) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39454,7 +39726,9 @@ var ts; } else { ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -39500,11 +39774,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_2; + return type_1; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -39690,6 +39964,7 @@ var ts; // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 245 /* InterfaceDeclaration */); + ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -39720,7 +39995,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length === 1) { var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -40427,8 +40702,8 @@ var ts; var decl = _a[_i]; var members = ts.getMembersOfDeclaration(decl); if (members) { - for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { - var member = members_4[_b]; + for (var _b = 0, members_5 = members; _b < members_5.length; _b++) { + var member = members_5[_b]; if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { lateBindMember(symbol, earlySymbols, lateSymbols, member); } @@ -40557,8 +40832,8 @@ var ts; var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + var sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -40566,15 +40841,13 @@ var ts; sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; } function cloneSignature(sig) { var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -40586,13 +40859,25 @@ var ts; result.mapper = undefined; return result; } - function createOptionalCallSignature(signature) { + function getOptionalCallSignature(signature, callChainFlags) { + if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) { + return signature; + } + if (!signature.optionalCallSignatureCache) { + signature.optionalCallSignatureCache = {}; + } + var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer"; + return signature.optionalCallSignatureCache[key] + || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags)); + } + function createOptionalCallSignature(signature, callChainFlags) { + ts.Debug.assert(callChainFlags === 4 /* IsInnerCallChain */ || callChainFlags === 8 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both."); var result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= callChainFlags; return result; } function getExpandedParameters(sig) { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { var restIndex_1 = sig.parameters.length - 1; var restParameter = sig.parameters[restIndex_1]; var restType = getTypeOfSymbol(restParameter); @@ -40617,7 +40902,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJSFile(baseTypeNode); @@ -40781,11 +41066,9 @@ var ts; var params = combineUnionParameters(left, right); var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - var hasRestParam = left.hasRestParameter || right.hasRestParameter; - var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */); result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); return result; } @@ -40958,7 +41241,7 @@ var ts; var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray; if (symbol.flags & 16 /* Function */) { constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) : undefined; })); } if (!constructSignatures.length) { @@ -41464,8 +41747,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_3 = types_6[_i]; - var baseType = getBaseConstraint(type_3); + var type_2 = types_6[_i]; + var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } @@ -41898,7 +42181,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var flags = 0 /* None */; var minArgumentCount = 0; var thisParameter = void 0; var hasThisParameter = false; @@ -41929,7 +42212,7 @@ var ts; parameters.push(paramSymbol); } if (type && type.kind === 186 /* LiteralType */) { - hasLiteralTypes = true; + flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || @@ -41955,9 +42238,11 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1 /* HasRestParameter */; + } links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, - /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -42100,8 +42385,11 @@ var ts; signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, /*wasOptional*/ true); + if (signature.flags & 4 /* IsInnerCallChain */) { + type = addOptionalTypeMarker(type); + } + else if (signature.flags & 8 /* IsOuterCallChain */) { + type = getOptionalType(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -42157,7 +42445,7 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, 1 /* Number */); @@ -42374,7 +42662,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 1835008 /* PropagatingFlags */; + return result & 3670016 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -42408,13 +42696,25 @@ var ts; return type; } function getTypeArguments(type) { + var _a, _b; if (!type.resolvedTypeArguments) { + if (!pushTypeResolution(type, 7 /* ResolvedTypeArguments */)) { + return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray; + } var node = type.node; var typeArguments = !node ? ts.emptyArray : node.kind === 168 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : node.kind === 173 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode); - type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + if (popTypeResolution()) { + type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + } + else { + type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray; + error(type.node || currentNode, type.target.symbol + ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves + : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol)); + } } return type.resolvedTypeArguments; } @@ -42531,7 +42831,7 @@ var ts; errorType; } if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) { - var jsdocType = getTypeFromJSAlias(node, symbol); + var jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -42544,18 +42844,30 @@ var ts; return errorType; } /** - * A JSdoc TypeReference may be to a value imported from commonjs. - * These should really be aliases, but this special-case code fakes alias resolution - * by producing a type from a value. + * A JSdoc TypeReference may be to a value, but resolve it as a type anyway. + * Note: If the value is imported from commonjs, it should really be an alias, + * but this function's special-case code fakes alias resolution as well. */ - function getTypeFromJSAlias(node, symbol) { + function getTypeFromJSDocValueReference(node, symbol) { var valueType = getTypeOfSymbol(symbol); - var typeType = valueType.symbol && - valueType.symbol !== symbol && // Make sure this is a commonjs export by checking that symbol -> type -> symbol doesn't roundtrip. - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + var typeType = valueType; + if (symbol.valueDeclaration) { + var decl = ts.getRootDeclaration(symbol.valueDeclaration); + var isRequireAlias = false; + if (ts.isVariableDeclaration(decl) && decl.initializer) { + var expr = decl.initializer; + // skip past entity names, eg `require("x").a.b.c` + while (ts.isPropertyAccessExpression(expr)) { + expr = expr.expression; + } + isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol; + } + var isImportTypeWithQualifier = node.kind === 187 /* ImportType */ && node.qualifier; + if (isRequireAlias || isImportTypeWithQualifier) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable, substitute) { if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === typeVariable) { @@ -42984,7 +43296,7 @@ var ts; if (type === wildcardType) includes |= 4194304 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 262144 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) includes |= 2097152 /* IncludesNonWideningType */; } else { @@ -43111,7 +43423,7 @@ var ts; neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 131072 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -43261,7 +43573,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) & 131072 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -43270,7 +43582,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 131072 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -43299,7 +43611,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 131072 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -44096,7 +44408,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host)) { + while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 137 /* ReadonlyKeyword */) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -44197,7 +44509,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ @@ -44511,7 +44823,7 @@ var ts; // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */); result.target = signature; result.mapper = mapper; return result; @@ -45392,20 +45704,20 @@ var ts; } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, - /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */; } /** * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any` */ function isAnySignature(s) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } /** * See signatureRelatedTo, compareSignaturesIdentical */ - function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) { // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; @@ -45424,6 +45736,9 @@ var ts; var sourceCount = getParameterCount(source); var sourceRestType = getNonArrayRestType(source); var targetRestType = getNonArrayRestType(target); + if (sourceRestType || targetRestType) { + void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers); + } if (sourceRestType && targetRestType && sourceCount !== targetCount) { // We're not able to relate misaligned complex rest parameters return 0 /* False */; @@ -45467,7 +45782,7 @@ var ts; (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); var related = callbacks ? // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is - compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) : + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { @@ -45481,13 +45796,13 @@ var ts; // If a signature resolution is already in-flight, skip issuing a circularity error // here and just use the `any` type directly var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType - : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(target.declaration.symbol) + : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol)) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType - : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(source.declaration.symbol) + : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol)) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); @@ -45674,7 +45989,7 @@ var ts; return true; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var related = relation.get(getRelationKey(source, target, relation)); + var related = relation.get(getRelationKey(source, target, /*isIntersectionConstituent*/ false, relation)); if (related !== undefined) { return !!(related & 1 /* Succeeded */); } @@ -46045,7 +46360,7 @@ var ts; // and we need to handle "each" relations before "some" relations for the same kind of type. if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), isIntersectionConstituent) : + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); } else { @@ -46083,7 +46398,7 @@ var ts; // // - For a primitive type or type parameter (such as 'number = A & B') there is no point in // breaking the intersection apart. - result = someTypeRelatedToType(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ true); + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { @@ -46196,7 +46511,7 @@ var ts; // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) - if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration)) { + if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) { // Note that extraneous children (as in `extra`) don't pass this check, // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute. errorNode = prop.valueDeclaration.name; @@ -46207,7 +46522,7 @@ var ts; // use the property's value declaration if the property is assigned inside the literal itself var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; - if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) { var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; @@ -46367,14 +46682,14 @@ var ts; } return result; } - function someTypeRelatedToType(source, target, reportErrors, isIntersectionConstituent) { + function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; for (var i = 0; i < len; i++) { - var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, isIntersectionConstituent); + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { return related; } @@ -46462,7 +46777,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, relation); + var id = getRelationKey(source, target, isIntersectionConstituent, relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -47356,7 +47671,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, incompatibleReporter, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, incompatibleReporter, isRelatedTo, reportUnreliableMarkers); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -47648,17 +47963,18 @@ var ts; * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. * For other cases, the types ids are used. */ - function getRelationKey(source, target, relation) { + function getRelationKey(source, target, isIntersectionConstituent, relation) { if (relation === identityRelation && source.id > target.id) { var temp = source; source = target; target = temp; } + var intersection = isIntersectionConstituent ? "&" : ""; if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { var typeParameters = []; - return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + intersection; } - return source.id + "," + target.id; + return source.id + "," + target.id + intersection; } // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. @@ -47709,7 +48025,7 @@ var ts; // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`). function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 524288 /* Object */) { + if (depth >= 5 && type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { var symbol = type.symbol; if (symbol) { var count = 0; @@ -48084,37 +48400,19 @@ var ts; function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type) { + return type !== optionalType; + } function removeOptionalTypeMarker(type) { - return strictNullChecks ? filterType(type, function (t) { return t !== optionalType; }) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } - function propagateOptionalTypeMarker(type, wasOptional) { - return wasOptional ? addOptionalTypeMarker(type) : type; + function propagateOptionalTypeMarker(type, node, wasOptional) { + return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional, type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - function checkOptionalExpression(parent, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var isOptional = false; - var type = checkExpression(expression); - if (ts.isOptionalChain(parent)) { - if (parent.questionDotToken) { - // If we have a questionDotToken then we are an OptionalExpression and should remove `null` and - // `undefined` from the type and add the optionalType to the result, if needed. - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - // If we do not have a questionDotToken, then we are an OptionalChain and we remove the optionalType and - // indicate whether we need to add optionalType back into the result. - var nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType, expression) { + return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } /** * Is source potentially coercible to target type under `==`. @@ -48268,14 +48566,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 */ | 1048576 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* 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) & 786432 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -48320,7 +48618,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 262144 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -48346,7 +48644,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) & 262144 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -48426,7 +48724,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 262144 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -48543,7 +48841,7 @@ var ts; return !!(type.flags & 63176704 /* Instantiable */ || 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 */ || + objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { @@ -48598,7 +48896,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) & 1048576 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }); } function createReverseMappedType(source, target, constraint) { @@ -48749,10 +49047,7 @@ var ts; // inferring a type parameter constraint. Instead, make a lower priority inference from // the full source to whatever remains in the target. For example, when inferring from // string to 'string | T', make a lower priority inference of string for T. - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, 1 /* NakedTypeVariable */); return; } source = getUnionType(sources); @@ -48785,7 +49080,7 @@ 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) & 1048576 /* NonInferrableType */ || source === silentNeverType || (priority & 16 /* ReturnType */ && (source === autoType || source === autoArrayType))) { + if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === silentNeverType || (priority & 16 /* ReturnType */ && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -48852,10 +49147,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - var savePriority = priority; - priority |= 32 /* LiteralKeyof */; - inferFromTypes(empty, target.type); - priority = savePriority; + inferWithPriority(empty, target.type, 32 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -48907,6 +49199,12 @@ var ts; } } } + function inferWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -48972,6 +49270,18 @@ var ts; } return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types) { + var typeVariable; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var type = types_13[_i]; + var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } function inferToMultipleTypes(source, targets, targetFlags) { var typeVariableCount = 0; if (targetFlags & 1048576 /* Union */) { @@ -49001,6 +49311,16 @@ var ts; } } } + if (typeVariableCount === 0) { + // If every target is an intersection of types containing a single naked type variable, + // make a lower priority inference to that type variable. This handles inferring from + // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T. + var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */); + } + return; + } // If the target has a single naked type variable and no inference circularities were // encountered above (meaning we explored the types fully), create a union of the source // types from which no inferences have been made so far and infer from that union to the @@ -49032,15 +49352,12 @@ var ts; // we want to infer string for T, not Promise | string. For intersection types // we only infer to single naked type variables. if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) { - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) { var t = targets_4[_b]; if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, 1 /* NakedTypeVariable */); } } - priority = savePriority; } } function inferToMappedType(source, target, constraintType) { @@ -49061,14 +49378,12 @@ var ts; if (inference && !inference.isFixed) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - var savePriority = priority; // 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). - priority |= ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? - 4 /* PartialHomomorphicMappedType */ : 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? + 4 /* PartialHomomorphicMappedType */ : + 2 /* HomomorphicMappedType */); } } return true; @@ -49076,10 +49391,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. - var savePriority = priority; - priority |= 8 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, 8 /* 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 @@ -49188,7 +49500,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 1048576 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -49457,6 +49769,15 @@ var ts; } return false; } + function optionalChainContainsReference(source, target) { + while (ts.isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property // a possible discriminant if its type differs in the constituents of containing union type, and if every @@ -49577,8 +49898,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; result |= getTypeFacts(t); } return result; @@ -49947,8 +50268,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -50029,9 +50350,18 @@ var ts; // expressions are potential type predicate function calls. In order to avoid triggering // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. - var funcType = node.parent.kind === 225 /* ExpressionStatement */ ? getTypeOfDottedName(node.expression, /*diagnostic*/ undefined) : - node.expression.kind !== 101 /* SuperKeyword */ ? checkOptionalExpression(node, node.expression).type : - undefined; + var funcType = void 0; + if (node.parent.kind === 225 /* ExpressionStatement */) { + funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); + } + else if (node.expression.kind !== 101 /* SuperKeyword */) { + if (ts.isOptionalChain(node)) { + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */); var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -50044,6 +50374,13 @@ var ts; return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */); } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { + return callExpression.arguments[predicate.parameterIndex]; + } + var invokedExpression = ts.skipParentheses(callExpression.expression); + return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined; + } function reportFlowControlError(node) { var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); var sourceFile = ts.getSourceFileOfNode(node); @@ -50059,6 +50396,11 @@ var ts; function isUnlockedReachableFlowNode(flow) { return !(flow.flags & 4096 /* PreFinally */ && flow.lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); } + function isFalseExpression(expr) { + var node = ts.skipParentheses(expr); + return node.kind === 90 /* FalseKeyword */ || node.kind === 208 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); + } function isReachableFlowNodeWorker(flow, noCacheCheck) { while (true) { if (flow === lastFlowNode) { @@ -50078,8 +50420,17 @@ var ts; } else if (flags & 512 /* Call */) { var signature = getEffectsSignature(flow.node); - if (signature && getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { - return false; + if (signature) { + var predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3 /* AssertsIdentifier */) { + var predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { + return false; + } } flow = flow.antecedent; } @@ -50313,6 +50664,9 @@ var ts; } function narrowTypeByAssertion(type, expr) { var node = ts.skipParentheses(expr); + if (node.kind === 90 /* FalseKeyword */) { + return unreachableNeverType; + } if (node.kind === 208 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); @@ -50331,7 +50685,7 @@ var ts; var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : - predicate.kind === 3 /* AssertsIdentifier */ ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -50402,17 +50756,24 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } else if (expr.kind === 203 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); + } + else if (expr.kind === 203 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -50420,6 +50781,7 @@ var ts; var antecedentTypes = []; var subtypeReduction = false; var seenIncomplete = false; + var bypassFlow; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; if (antecedent.flags & 4096 /* PreFinally */ && antecedent.lock.locked) { @@ -50428,6 +50790,11 @@ var ts; // in this case we should ignore this branch. continue; } + if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) { + // The antecedent is the bypass branch of a potentially exhaustive switch statement. + bypassFlow = antecedent; + continue; + } var flowType = getTypeAtFlowNode(antecedent); var type = getTypeFromFlowType(flowType); // If the type at a particular antecedent path is the declared type and the @@ -50448,6 +50815,25 @@ var ts; seenIncomplete = true; } } + if (bypassFlow) { + var flowType = getTypeAtFlowNode(bypassFlow); + var type = getTypeFromFlowType(flowType); + // If the bypass flow contributes a type we haven't seen yet and the switch statement + // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase + // the risk of circularities, we only want to perform them when they make a difference. + if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) { + if (type === declaredType && declaredType === initialType) { + return type; + } + antecedentTypes.push(type); + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + } return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { @@ -50554,6 +50940,9 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } @@ -50602,6 +50991,14 @@ var ts; if (isMatchingReference(reference, right_1)) { return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + } + else if (optionalChainContainsReference(right_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left_1, declaredType)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } @@ -50625,6 +51022,15 @@ var ts; } return type; } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + // We are in a branch of obj?.foo === value or obj?.foo !== value. We remove undefined and null from + // the type of obj if (a) the operator is === and the type of value doesn't include undefined or (b) the + // operator is !== and the type of value is undefined. + var effectiveTrue = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */ ? assumeTrue : !assumeTrue; + var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */; + var valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? 262144 /* EQUndefinedOrNull */ : 65536 /* EQUndefined */)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* Any */) { return type; @@ -50672,8 +51078,14 @@ var ts; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands + if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, target)) { @@ -50681,9 +51093,6 @@ var ts; } return type; } - if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } @@ -50716,6 +51125,10 @@ var ts; return type; } } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { + var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify // values with unit types, except for the case where @@ -50848,6 +51261,9 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' // references might reference a different 'y' property. However, we make an exception @@ -50920,39 +51336,28 @@ var ts; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + var predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (ts.isAccessExpression(invokedExpression) && predicate.type) { - var possibleReference = ts.skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if (ts.isOptionalChainRoot(expr.parent) || + if (ts.isExpressionOfOptionalChainRoot(expr) || ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -51233,7 +51638,24 @@ var ts; } } else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { - error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + var diag = error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // See GH:32846 - if the user is using a variable whose type is () => T1 | ... | undefined + // they may have meant to specify the type as (() => T1 | ...) | undefined + // This is assumed if: the type is a FunctionType, the return type is a Union, the last constituent of + // the union is `undefined` + if (type.symbol && type.symbol.declarations.length === 1 && ts.isFunctionTypeNode(type.symbol.declarations[0])) { + var funcTypeNode = type.symbol.declarations[0]; + var returnType = getReturnTypeFromAnnotation(funcTypeNode); + if (returnType && returnType.flags & 1048576 /* Union */) { + var unionTypes_3 = funcTypeNode.type.types; + if (unionTypes_3 && unionTypes_3[unionTypes_3.length - 1].kind === 145 /* UndefinedKeyword */) { + var parenedFuncType = ts.getMutableClone(funcTypeNode); + // Highlight to the end of the second to last constituent of the union + parenedFuncType.end = unionTypes_3[unionTypes_3.length - 2].end; + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(parenedFuncType, ts.Diagnostics.Did_you_mean_to_parenthesize_this_function_type)); + } + } + } // Return the declared type to reduce follow-on errors return type; } @@ -52013,18 +52435,22 @@ var ts; return undefined; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget, arg) { + function getContextualTypeForArgument(callTarget, arg, contextFlags) { var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + function getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & 4 /* Completion */ && signature.target) { + var baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { @@ -52383,7 +52809,7 @@ var ts; } /* falls through */ case 196 /* NewExpression */: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case 198 /* TypeAssertionExpression */: case 216 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); @@ -52598,8 +53024,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -52700,7 +53126,7 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; } return literalType; } @@ -52837,7 +53263,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 1835008 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -52946,7 +53372,7 @@ 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 */ | 524288 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { result.objectFlags |= 16384 /* JSLiteral */; } @@ -53044,7 +53470,7 @@ var ts; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 1835008 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -53124,7 +53550,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 */ | 524288 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -53596,8 +54022,8 @@ var ts; function symbolHasNonMethodDeclaration(symbol) { return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } - function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */); @@ -53605,22 +54031,34 @@ var ts; function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + function reportObjectPossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + } + function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? - (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + reportError(node, kind); var t = getNonNullableType(type); return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) { @@ -53629,10 +54067,16 @@ var ts; return nonNullType; } function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + function checkPropertyAccessChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); } function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node) { while (node.parent.kind === 199 /* ParenthesizedExpression */) { @@ -53640,8 +54084,7 @@ var ts; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var _a = checkOptionalExpression(node, left), isOptional = _a.isOptional, leftType = _a.type; + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -53694,7 +54137,7 @@ var ts; } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { // Only compute control flow type if this is a property access expression that isn't an @@ -54016,7 +54459,15 @@ var ts; return false; } function checkIndexedAccess(node) { - var _a = checkOptionalExpression(node, node.expression), isOptional = _a.isOptional, exprType = _a.type; + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + function checkElementAccessChain(node) { + var exprType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -54032,7 +54483,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -54103,7 +54554,7 @@ var ts; // interface B extends A { (x: 'foo'): string } // const b: B; // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] - function reorderCandidates(signatures, result, isOptionalCall) { + function reorderCandidates(signatures, result, callChainFlags) { var lastParent; var lastSymbol; var cutoffIndex = 0; @@ -54133,7 +54584,7 @@ var ts; lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -54144,7 +54595,7 @@ var ts; else { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature); } } function isSpreadArgument(arg) { @@ -54228,7 +54679,7 @@ var ts; // the declared number of type parameters, the call has an incorrect arity. var numTypeParameters = ts.length(signature.typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - return !typeArguments || + return !ts.some(typeArguments) || (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. @@ -54439,7 +54890,19 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var thisArgumentType = void 0; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (ts.isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -54666,7 +55129,7 @@ var ts; 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.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_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 (min < argCount && argCount < max) { @@ -54722,7 +55185,7 @@ var ts; } return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } - function resolveCall(node, signatures, candidatesOutArray, checkMode, isOptionalCall, fallbackError) { + function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { var isTaggedTemplate = node.kind === 197 /* TaggedTemplateExpression */; var isDecorator = node.kind === 156 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -54737,7 +55200,7 @@ var ts; } var candidates = candidatesOutArray || []; // reorderCandidates fills up the candidates array directly - reorderCandidates(signatures, candidates, isOptionalCall); + reorderCandidates(signatures, candidates, callChainFlags); if (!candidates.length) { if (reportErrors) { diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); @@ -54899,7 +55362,7 @@ var ts; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) { @@ -54917,7 +55380,7 @@ var ts; var inferenceContext = void 0; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - if (typeArguments) { + if (ts.some(typeArguments)) { typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); if (!typeArgumentTypes) { candidateForTypeArgumentError = candidate; @@ -54992,34 +55455,34 @@ var ts; var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; var _loop_15 = function (i) { - var symbols = ts.mapDefined(candidates, function (_a) { - var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; - return hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : - i < parameters.length ? parameters[i] : undefined; - }); + var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined; }); ts.Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { _loop_15(i); } - var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); - var hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); + var flags = 0 /* None */; + if (restParameterSymbols.length !== 0) { var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1 /* HasRestParameter */; + } + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2 /* HasLiteralTypes */; } return createSignature(candidates[0].declaration, /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. thisParameter, parameters, /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), - /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, - /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + /*typePredicate*/ undefined, minArgumentCount, flags); } function getNumNonRestParameters(signature) { var numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); @@ -55095,12 +55558,24 @@ var ts; var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */); } } return resolveUntypedCall(node); } - var _b = checkOptionalExpression(node, node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined), isOptional = _b.isOptional, funcType = _b.type; + var callChainFlags; + var funcType = checkExpression(node.expression); + if (ts.isCallChain(node)) { + var nonOptionalType = getOptionalExpressionType(funcType, node.expression); + callChainFlags = nonOptionalType === funcType ? 0 /* None */ : + ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ : + 4 /* IsInnerCallChain */; + funcType = nonOptionalType; + } + else { + callChainFlags = 0 /* None */; + } + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -55166,7 +55641,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, isOptional); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags); } function isGenericFunctionReturningFunction(signature) { return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature))); @@ -55229,7 +55704,7 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */); } // If expressionType's apparent type is an object type with no construct signatures but // one or more call signatures, the expression is processed as a function call. A compile-time @@ -55237,7 +55712,7 @@ var ts; // operation is Any. It is an error to have a Void this type. var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); if (!noImplicitAny) { if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); @@ -55322,8 +55797,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var constituent = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var constituent = types_17[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -55414,7 +55889,7 @@ var ts; invocationError(node.tag, apparentType, 0 /* Call */); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); } /** * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. @@ -55467,7 +55942,7 @@ var ts; invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage); } function createSignatureForJSXIntrinsic(node, result) { var namespace = getJsxNamespaceAt(node); @@ -55482,9 +55957,7 @@ var ts; return createSignature(declaration, /*typeParameters*/ undefined, /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, - /*returnTypePredicate*/ undefined, 1, - /*hasRestparameter*/ false, - /*hasLiteralTypes*/ false); + /*returnTypePredicate*/ undefined, 1, 0 /* None */); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -55507,7 +55980,7 @@ var ts; error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); return resolveErrorCall(node); } - return resolveCall(node, signatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */); } /** * Sometimes, we have a decorator that could accept zero arguments, @@ -55517,7 +55990,7 @@ var ts; function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } @@ -55588,7 +56061,7 @@ var ts; return false; } function mergeJSSymbols(target, source) { - if (source && (ts.hasEntries(source.exports) || ts.hasEntries(source.members))) { + if (source) { var links = getSymbolLinks(source); if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) { var inferred = isTransientSymbol(target) ? target : cloneSymbol(target); @@ -55898,7 +56371,7 @@ var ts; return type; } function getParameterNameAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -55915,11 +56388,11 @@ var ts; return tryGetTypeAtPosition(signature, pos) || anyType; } function tryGetTypeAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // We want to return the value undefined for an out of bounds parameter position, // so we need to check bounds here before calling getIndexedAccessType (which // otherwise would return the type 'undefined'). @@ -55954,7 +56427,7 @@ var ts; } function getParameterCount(signature) { var length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -55963,7 +56436,7 @@ var ts; return length; } function getMinArgumentCount(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { var minLength = restType.target.minLength; @@ -55975,14 +56448,14 @@ var ts; return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } return false; } function getEffectiveRestType(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -55999,7 +56472,7 @@ var ts; return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, inferenceContext) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -56032,7 +56505,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } } - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56040,7 +56513,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56317,8 +56790,8 @@ var ts; var witnesses = getSwitchClauseTypeOfWitnesses(node); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_4 = getBaseConstraintOfType(operandType) || operandType; - return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + var type_3 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -56445,9 +56918,9 @@ var ts; return links.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + 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 |= 1048576 /* NonInferrableType */; + returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } return anyFunctionType; @@ -56676,8 +57149,7 @@ var ts; var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); var func = ts.getContainingFunction(node); - if (func && func.kind !== 161 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + if (func && func.kind !== 161 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -56778,8 +57250,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -57413,25 +57885,10 @@ var ts; } return [effectiveLeft, effectiveRight]; } - function isYieldExpressionInClass(node) { - var current = node; - var parent = node.parent; - while (parent) { - if (ts.isFunctionLike(parent) && current === parent.body) { - return false; - } - else if (ts.isClassLike(current)) { - return true; - } - current = parent; - parent = parent.parent; - } - return false; - } function checkYieldExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 8192 /* YieldContext */) || isYieldExpressionInClass(node)) { + if (!(node.flags & 8192 /* YieldContext */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -57767,6 +58224,18 @@ var ts; } } } + function getReturnTypeOfSingleNonGenericCallSignature(funcType) { + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) { + var funcType = checkExpression(expr.expression); + var nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType); + return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType); + } /** * Returns the type of an expression. Unlike checkExpression, this function is simply concerned * with computing the type and may not fully check all contained sub-expressions for errors. @@ -57778,10 +58247,10 @@ var ts; // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. if (ts.isCallExpression(expr) && expr.expression.kind !== 101 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { - var _a = checkOptionalExpression(expr, expr.expression), isOptional = _a.isOptional, funcType = _a.type; - var signature = getSingleCallSignature(funcType); - if (signature && !signature.typeParameters) { - return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); + var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : + getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression)); + if (type) { + return type; } } else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) { @@ -57831,7 +58300,7 @@ var ts; (node.parent.kind === 194 /* ElementAccessExpression */ && node.parent.expression === node) || ((node.kind === 75 /* Identifier */ || node.kind === 152 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || (node.parent.kind === 171 /* TypeQuery */ && node.parent.exprName === node)) || - (node.parent.kind === 261 /* ExportSpecifier */ && (compilerOptions.preserveConstEnums || node.flags & 8388608 /* Ambient */)); // We allow reexporting const enums + (node.parent.kind === 261 /* ExportSpecifier */); // We allow reexporting const enums if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -58035,7 +58504,7 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -59210,7 +59679,7 @@ var ts; return; } // Verify there is no local declaration that could collide with the promise constructor. - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); @@ -59267,7 +59736,7 @@ var ts; function markEntityNameOrEntityExpressionAsReference(typeName) { if (!typeName) return; - var rootName = getFirstIdentifier(typeName); + var rootName = ts.getFirstIdentifier(typeName); var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol @@ -59307,8 +59776,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var typeNode = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var typeNode = types_19[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -61083,10 +61552,7 @@ var ts; firstDefaultClause = clause; } else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -61107,6 +61573,9 @@ var ts; } } ts.forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -61629,11 +62098,13 @@ var ts; // same when the derived property is from an assignment continue; } - if (basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property; - } - else if (basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor; + var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */; + var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */; + if (overriddenInstanceProperty || overriddenInstanceAccessor) { + var errorMessage_1 = overriddenInstanceProperty ? + ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : + 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 { var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 158 /* PropertyDeclaration */ && !d.initializer; }); @@ -61649,24 +62120,22 @@ var ts; || !ts.isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { - var errorMessage_1 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; - error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType)); + var errorMessage_2 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType)); } } - // correct case - continue; } + // correct case + continue; } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { - // method is overridden with method -- correct case + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { + // method is overridden with method or property -- correct case continue; } - else if (derived.flags & 98304 /* Accessor */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & 98304 /* Accessor */) { @@ -62172,22 +62641,6 @@ var ts; break; } } - function getFirstIdentifier(node) { - switch (node.kind) { - case 75 /* Identifier */: - return node; - case 152 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 75 /* Identifier */); - return node; - case 193 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 75 /* Identifier */); - return node; - } - } function getFirstNonModuleExportsIdentifier(node) { switch (node.kind) { case 75 /* Identifier */: @@ -62317,7 +62770,7 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - var moduleName = getFirstIdentifier(node.moduleReference); + var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } @@ -62384,7 +62837,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -64690,10 +65143,10 @@ var ts; if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -65576,7 +66029,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -65646,6 +66099,14 @@ var ts; case 2 /* Next */: return "nextType"; } } + function signatureHasRestParameter(s) { + return !!(s.flags & 1 /* HasRestParameter */); + } + ts.signatureHasRestParameter = signatureHasRestParameter; + function signatureHasLiteralTypes(s) { + return !!(s.flags & 2 /* HasLiteralTypes */); + } + ts.signatureHasLiteralTypes = signatureHasLiteralTypes; })(ts || (ts = {})); var ts; (function (ts) { @@ -66579,7 +67040,9 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } // Because we are updating existed propertyAccess we want to inherit its emitFlags // instead of using the default from createPropertyAccess return node.expression !== expression @@ -66617,7 +67080,9 @@ var ts; } ts.createElementAccess = createElementAccess; function updateElementAccess(node, expression, argumentExpression) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -66651,7 +67116,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (ts.isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -67253,7 +67720,7 @@ var ts; var node = createSynthesizedNode(231 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -69779,7 +70246,7 @@ var ts; var conditionalPrecedence = ts.getOperatorPrecedence(209 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { return ts.createParen(condition); } return condition; @@ -70377,6 +70844,12 @@ var ts; * Gets the property name of a BindingOrAssignmentElement */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement); + ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element."); + return propertyName; + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { case 190 /* BindingElement */: // `a` in `let { a: b } = ...` @@ -70412,9 +70885,8 @@ var ts; ? target.expression : target; } - ts.Debug.fail("Invalid property name for binding element."); } - ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; function isStringOrNumericLiteral(node) { var kind = node.kind; return kind === 10 /* StringLiteral */ @@ -72433,7 +72905,8 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node)) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); @@ -72502,6 +72975,17 @@ var ts; } return false; } + function bindingOrAssignmentElementContainsNonLiteralComputedName(element) { + var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element); + if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) { + return true; + } + var target = ts.getTargetOfBindingOrAssignmentElement(element); + return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target); + } + function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) { + return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName); + } /** * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * @@ -72532,7 +73016,8 @@ var ts; }; if (ts.isVariableDeclaration(node)) { var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); - if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node))) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); @@ -73831,8 +74316,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { - var member = members_5[_i]; + for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { + var member = members_6[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -74222,8 +74707,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -74835,7 +75320,12 @@ var ts; * * @param node The module declaration node. */ - function shouldEmitModuleDeclaration(node) { + function shouldEmitModuleDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration); + if (!node) { + // If we can't find a parse tree node, assume the node is instantiated. + return true; + } return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } /** @@ -75654,7 +76144,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); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -77411,7 +77901,7 @@ var ts; } return ts.updateParen(node, expression); } - function visitNonOptionalPropertyAccessExpression(node, captureThisArg) { + function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg) { if (ts.isOptionalChain(node)) { // If `node` is an optional chain, then it is the outermost chain of an optional expression. return visitOptionalExpression(node, captureThisArg); @@ -77420,27 +77910,17 @@ var ts; ts.Debug.assertNotNode(expression, ts.isSyntheticReference); var thisArg; if (captureThisArg) { - // `a.b` -> { expression: `(_a = a).b`, thisArg: `_a` } - thisArg = ts.createTempVariable(hoistVariableDeclaration); - expression = ts.createParen(ts.createAssignment(thisArg, expression)); + if (shouldCaptureInTempVariable(expression)) { + thisArg = ts.createTempVariable(hoistVariableDeclaration); + expression = ts.createAssignment(thisArg, expression); + } + else { + thisArg = expression; + } } - expression = ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)); - return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression; - } - function visitNonOptionalElementAccessExpression(node, captureThisArg) { - if (ts.isOptionalChain(node)) { - // If `node` is an optional chain, then it is the outermost chain of an optional expression. - return visitOptionalExpression(node, captureThisArg); - } - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - ts.Debug.assertNotNode(expression, ts.isSyntheticReference); - var thisArg; - if (captureThisArg) { - // `a[b]` -> { expression: `(_a = a)[b]`, thisArg: `_a` } - thisArg = ts.createTempVariable(hoistVariableDeclaration); - expression = ts.createParen(ts.createAssignment(thisArg, expression)); - } - expression = ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); + expression = node.kind === 193 /* PropertyAccessExpression */ + ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) + : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression; } function visitNonOptionalCallExpression(node, captureThisArg) { @@ -77453,8 +77933,8 @@ var ts; function visitNonOptionalExpression(node, captureThisArg) { switch (node.kind) { case 199 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg); - case 193 /* PropertyAccessExpression */: return visitNonOptionalPropertyAccessExpression(node, captureThisArg); - case 194 /* ElementAccessExpression */: return visitNonOptionalElementAccessExpression(node, captureThisArg); + case 193 /* PropertyAccessExpression */: + case 194 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg); case 195 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } @@ -77462,31 +77942,36 @@ var ts; function visitOptionalExpression(node, captureThisArg) { var _a = flattenChain(node), expression = _a.expression, chain = _a.chain; var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0])); - var temp = ts.createTempVariable(hoistVariableDeclaration); var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined; var leftExpression = ts.isSyntheticReference(left) ? left.expression : left; - var rightExpression = temp; + var capturedLeft = leftExpression; + if (shouldCaptureInTempVariable(leftExpression)) { + capturedLeft = ts.createTempVariable(hoistVariableDeclaration); + leftExpression = ts.createAssignment(capturedLeft, leftExpression); + } + var rightExpression = capturedLeft; var thisArg; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { case 193 /* PropertyAccessExpression */: - if (i === chain.length - 1 && captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - rightExpression = ts.createParen(ts.createAssignment(thisArg, rightExpression)); - } - rightExpression = ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)); - break; case 194 /* ElementAccessExpression */: if (i === chain.length - 1 && captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - rightExpression = ts.createParen(ts.createAssignment(thisArg, rightExpression)); + if (shouldCaptureInTempVariable(rightExpression)) { + thisArg = ts.createTempVariable(hoistVariableDeclaration); + rightExpression = ts.createAssignment(thisArg, rightExpression); + } + else { + thisArg = rightExpression; + } } - rightExpression = ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); + rightExpression = segment.kind === 193 /* PropertyAccessExpression */ + ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) + : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; case 195 /* CallExpression */: if (i === 0 && leftThisArg) { - rightExpression = ts.createFunctionCall(rightExpression, leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); + rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 101 /* SuperKeyword */ ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } else { rightExpression = ts.createCall(rightExpression, @@ -77496,22 +77981,27 @@ var ts; } ts.setOriginalNode(rightExpression, segment); } - var target = ts.createConditional(ts.createLogicalOr(ts.createStrictEquality(ts.createAssignment(temp, leftExpression), ts.createNull()), ts.createStrictEquality(temp, ts.createVoidZero())), ts.createVoidZero(), rightExpression); + var target = ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createVoidZero(), rightExpression); return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target; } - function createNotNullCondition(node) { - return ts.createBinary(ts.createBinary(node, ts.createToken(37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(55 /* AmpersandAmpersandToken */), ts.createBinary(node, ts.createToken(37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero())); + function createNotNullCondition(left, right, invert) { + return ts.createBinary(ts.createBinary(left, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(invert ? 56 /* BarBarToken */ : 55 /* AmpersandAmpersandToken */), ts.createBinary(right, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero())); } function transformNullishCoalescingExpression(node) { - var expressions = []; var left = ts.visitNode(node.left, visitor, ts.isExpression); - if (!ts.isIdentifier(left)) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - expressions.push(ts.createAssignment(temp, left)); - left = temp; + var right = left; + if (shouldCaptureInTempVariable(left)) { + right = ts.createTempVariable(hoistVariableDeclaration); + left = ts.createAssignment(right, left); } - expressions.push(ts.createParen(ts.createConditional(createNotNullCondition(left), left, ts.visitNode(node.right, visitor, ts.isExpression)))); - return ts.inlineExpressions(expressions); + return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression)); + } + function shouldCaptureInTempVariable(expression) { + // don't capture identifiers and `this` in a temporary variable + // `super` cannot be captured as it's no real variable + return !ts.isIdentifier(expression) && + expression.kind !== 103 /* ThisKeyword */ && + expression.kind !== 101 /* SuperKeyword */; } } ts.transformESNext = transformESNext; @@ -87669,6 +88159,7 @@ var ts; var combinedStatements; if (ts.isSourceFileJS(currentSourceFile)) { combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); } else { @@ -89440,7 +89931,11 @@ var ts; bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) + return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) + emitSkipped = true; return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -92194,8 +92689,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_20 = types; _d < types_20.length; _d++) { - var directive = types_20[_d]; + for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { + var directive = types_21[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -94070,31 +94565,39 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (system.directoryExists(directoryPath)) { + if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } return false; } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - if (compilerHost.createDirectory) { - compilerHost.createDirectory(directoryPath); - } - else { - system.createDirectory(directoryPath); + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + // NOTE: If patchWriteFileEnsuringDirectory has been called, + // the system.writeFile will do its own directory creation and + // the ensureDirectoriesExist call will always be redundant. + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); } } } var outputFingerprints; - function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + function writeFileWorker(fileName, data, writeByteOrderMark) { + if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) { + system.writeFile(fileName, data, writeByteOrderMark); + return; + } if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = system.createHash(data); // TODO: GH#18217 - var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); + var mtimeBefore = system.getModifiedTime(fileName); if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -94106,32 +94609,13 @@ var ts; } } system.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, mtime: mtimeAfter }); } - function writeFile(fileName, data, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { - writeFileIfUpdated(fileName, data, writeByteOrderMark); - } - else { - system.writeFile(fileName, data, writeByteOrderMark); - } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -95853,9 +96337,16 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - if (fail) - fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + var canonicalFileName_1 = host.getCanonicalFileName(fileName); + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) { + if (fail) { + if (ts.hasJSFileExtension(canonicalFileName_1)) { + fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName); + } + else { + fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + } + } return undefined; } var sourceFile = getSourceFile(fileName); @@ -95869,7 +96360,7 @@ var ts; fail(ts.Diagnostics.File_0_not_found, fileName); } } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) { fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); } } @@ -95927,6 +96418,19 @@ var ts; function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) { if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(fileName); + // If preserveSymlinks is true, module resolution wont jump the symlink + // but the resolved real path may be the .d.ts from project reference + // Note:: Currently we try the real path only if the + // file is from node_modules to avoid having to run real path on all file paths + if (!source && + host.realpath && + options.preserveSymlinks && + ts.isDeclarationFileName(fileName) && + ts.stringContains(fileName, ts.nodeModulesPathPart)) { + var realPath = host.realpath(fileName); + if (realPath !== fileName) + source = getSourceOfProjectReferenceRedirect(realPath); + } if (source) { var file_1 = ts.isString(source) ? findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) : @@ -96457,9 +96961,6 @@ var ts; else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && ts.isIncrementalCompilation(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { @@ -97504,6 +98005,7 @@ var ts; ts.Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = ts.createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -98234,7 +98736,7 @@ var ts; } var state = { fileInfos: fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), @@ -98270,33 +98772,6 @@ var ts; } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; - function convertFromReusableCompilerOptions(options, toAbsolutePath) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - function convertFromReusableCompilerOptionValue(option, value, toAbsolutePath) { - if (option) { - if (option.type === "list") { - var values = value; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value); - } - } - return value; - } function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -99029,7 +99504,7 @@ var ts; function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { return { relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, - ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? + ending: ts.hasJSFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, }; @@ -99115,7 +99590,7 @@ var ts; var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } function numberOfDirectorySeparators(str) { @@ -99249,10 +99724,13 @@ var ts; // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); + var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { return undefined; + } // If the module was found in @types, get the actual Node package name var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); @@ -99477,7 +99955,7 @@ var ts; /** Parses config file using System interface */ function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; @@ -99501,7 +99979,7 @@ var ts; } ts.getErrorSummaryText = getErrorSummaryText; function listFiles(program, writeFileName) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { ts.forEach(program.getSourceFiles(), function (file) { writeFileName(file.fileName); }); @@ -99512,6 +99990,7 @@ var ts; * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -99520,13 +99999,17 @@ var ts; // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + if (!isListFilesOnly) { + ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + } } } // Emit and report any errors we ran into. - var emitResult = program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + var emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: ts.emptyArray } + : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics; ts.addRange(diagnostics, emitDiagnostics); ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); @@ -99629,19 +100112,13 @@ var ts; createHash: ts.maybeBind(host, host.createHash), readDirectory: ts.maybeBind(host, host.readDirectory), }; - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - if (host.createDirectory) - host.createDirectory(directoryPath); - } - } function writeFile(fileName, text, writeByteOrderMark, onError) { try { ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); + // NOTE: If patchWriteFileEnsuringDirectory has been called, + // the host.writeFile will do its own directory creation and + // the ensureDirectoriesExist call will always be redundant. + ts.writeFileEnsuringDirectories(fileName, text, writeByteOrderMark, function (path, data, writeByteOrderMark) { return host.writeFile(path, data, writeByteOrderMark); }, function (path) { return host.createDirectory(path); }, function (path) { return host.directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -101418,30 +101895,25 @@ var ts; setupInitialBuild(state, cancellationToken); var reportQueue = true; var successfulProjects = 0; - var errorProjects = 0; while (true) { var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; - } } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ts.ExitStatus.DiagnosticsPresent_OutputsGenerated : - ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : - ts.ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); }) + ? ts.ExitStatus.Success + : successfulProjects + ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated + : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); @@ -101449,7 +101921,7 @@ var ts; return ts.ExitStatus.InvalidProject_OutputsSkipped; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped; } var options = state.options, host = state.host; var filesToDelete = options.dry ? [] : undefined; @@ -103744,6 +104216,25 @@ var ts; return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); } ts.documentSpansEqual = documentSpansEqual; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + ts.forEachUnique = forEachUnique; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -104491,10 +104982,11 @@ var ts; } var dependencyKeys = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]; var stringContent = host.readFile(fileName); - var content = stringContent && tryParseJson(stringContent); - if (!content) { + if (!stringContent) return undefined; - } + var content = tryParseJson(stringContent); + if (!content) + return false; var info = {}; for (var _i = 0, dependencyKeys_1 = dependencyKeys; _i < dependencyKeys_1.length; _i++) { var key = dependencyKeys_1[_i]; @@ -105019,8 +105511,10 @@ var ts; }); return { spans: spans, endOfLineState: 0 /* None */ }; function pushClassification(start, end, type) { + var length = end - start; + ts.Debug.assert(length > 0, "Classification had non-positive length of " + length); spans.push(start); - spans.push(end - start); + spans.push(length); spans.push(type); } } @@ -105439,8 +105933,7 @@ var ts; return 25 /* bigintLiteral */; } else if (tokenKind === 10 /* StringLiteral */) { - // TODO: GH#18217 - return token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token && token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -105698,7 +106191,7 @@ var ts; var candidates = []; checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); var types = ts.flatMap(candidates, function (candidate) { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); @@ -106848,6 +107341,7 @@ var ts; var completionKind = 5 /* None */; var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; + // This also gets mutated in nested-functions after the return var symbols = []; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; @@ -106954,8 +107448,15 @@ var ts; var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -106972,8 +107473,15 @@ var ts; var type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -107275,7 +107783,7 @@ var ts; typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); } /** - * Gathers symbols that can be imported from other files, deduplicating along the way. Symbols can be “duplicates” + * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, * if and only if the the first can be imported (it may be excluded due to package.json filtering in @@ -107351,7 +107859,7 @@ var ts; // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -107465,7 +107973,16 @@ var ts; } if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) { if (contextToken.parent.kind === 266 /* JsxOpeningElement */) { - return true; + // Two possibilities: + // 1.
/**/ + // - contextToken: GreaterThanToken (before cursor) + // - location: JSXElement + // - different parents (JSXOpeningElement, JSXElement) + // 2. /**/> + // - contextToken: GreaterThanToken (before cursor) + // - location: GreaterThanToken (after cursor) + // - same parent (JSXOpeningElement) + return location.parent.kind !== 266 /* JsxOpeningElement */; } if (contextToken.parent.kind === 267 /* JsxClosingElement */ || contextToken.parent.kind === 265 /* JsxSelfClosingElement */) { return !!contextToken.parent.parent && contextToken.parent.parent.kind === 264 /* JsxElement */; @@ -107540,7 +108057,7 @@ var ts; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 192 /* ObjectLiteralExpression */) { - var typeForObject = typeChecker.getContextualType(objectLikeContainer); + var typeForObject = typeChecker.getContextualType(objectLikeContainer, 4 /* Completion */); if (!typeForObject) return 2 /* Fail */; isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); @@ -108117,6 +108634,8 @@ var ts; return isFunctionLikeBodyKeyword(kind) || kind === 129 /* DeclareKeyword */ || kind === 134 /* ModuleKeyword */ + || kind === 144 /* TypeKeyword */ + || kind === 135 /* NamespaceKeyword */ || ts.isTypeKeyword(kind) && kind !== 145 /* UndefinedKeyword */; case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); @@ -109926,7 +110445,7 @@ var ts; return undefined; } function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet) { - var moduleSourceFile = symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; + var moduleSourceFile = (symbol.flags & 1536 /* Module */) && symbol.declarations && ts.find(symbol.declarations, ts.isSourceFile); if (!moduleSourceFile) return undefined; var exportEquals = symbol.exports.get("export=" /* ExportEquals */); @@ -110651,8 +111170,10 @@ var ts; || exportSpecifier.name.originalKeywordKind === 83 /* DefaultKeyword */; var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); - var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); - searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + var exportInfo = FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker); + if (exportInfo) { + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { @@ -111863,7 +112384,7 @@ var ts; // The property length will have two declarations of property length coming // from Array - Array and Array var documentationComment = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var comment = _a[_i].comment; if (comment === undefined) @@ -111892,7 +112413,7 @@ var ts; function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); @@ -111929,24 +112450,6 @@ var ts; return comment === undefined ? s : s + " " + comment; } } - /** - * Iterates through 'array' by index and performs the callback on each element of array until the callback - * returns a truthy value, then returns that value. - * If no such value is found, the callback is applied to each element of array and undefined is returned. - */ - function forEachUnique(array, callback) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array.indexOf(array[i]) === i) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - } - } - return undefined; - } function getJSDocTagNameCompletions() { return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { @@ -112871,7 +113374,8 @@ var ts; } var declName = ts.getNameOfDeclaration(node); if (declName && ts.isPropertyName(declName)) { - return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 + var propertyName = ts.getPropertyNameForPropertyNameNode(declName); + return propertyName && ts.unescapeLeadingUnderscores(propertyName); } switch (node.kind) { case 200 /* FunctionExpression */: @@ -113641,6 +114145,9 @@ var ts; case 265 /* JsxSelfClosingElement */: case 266 /* JsxOpeningElement */: return spanForJSXAttributes(n.attributes); + case 210 /* TemplateExpression */: + case 14 /* NoSubstitutionTemplateLiteral */: + return spanForTemplateLiteral(n); } function spanForJSXElement(node) { var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); @@ -113659,6 +114166,12 @@ var ts; } return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } + function spanForTemplateLiteral(node) { + if (node.kind === 14 /* NoSubstitutionTemplateLiteral */ && node.text.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); + } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 18 /* OpenBraceToken */; } // If the block has no leading keywords and is inside an array literal or call expression, @@ -115961,7 +116474,7 @@ var ts; // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration - var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + var locationIsSymbolDeclaration = symbol.declarations && ts.find(symbol.declarations, function (declaration) { return declaration === (location.kind === 128 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { @@ -116868,8 +117381,8 @@ var ts; rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */), // in other cases there should be no space between '?' and next token rule("NoSpaceAfterQuestionMark", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceBeforeDot", anyToken, [24 /* DotToken */, 28 /* QuestionDotToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceAfterDot", [24 /* DotToken */, 28 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBetweenImportParenInImportType", 95 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between @@ -119001,7 +119514,10 @@ var ts; if (ts.isCallOrNewExpression(parent)) { if (!parent.arguments) return false; - var currentNode = ts.Debug.assertDefined(ts.find(parent.arguments, function (arg) { return arg.pos === child.pos; })); + var currentNode = ts.find(parent.arguments, function (arg) { return arg.pos === child.pos; }); + // If it's not one of the arguments, don't look past this + if (!currentNode) + return false; var currentIndex = parent.arguments.indexOf(currentNode); if (currentIndex === 0) return false; // Can't look at previous node if first @@ -119420,6 +119936,18 @@ var ts; cb(tracker); return tracker.getChanges(); }; + ChangeTracker.prototype.pushRaw = function (sourceFile, change) { + ts.Debug.assertEqual(sourceFile.fileName, change.fileName); + for (var _i = 0, _a = change.textChanges; _i < _a.length; _i++) { + var c = _a[_i]; + this.changes.push({ + kind: ChangeKind.Text, + sourceFile: sourceFile, + text: c.newText, + range: ts.createTextRangeFromSpan(c.span), + }); + } + }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); }; @@ -119548,7 +120076,7 @@ var ts; endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); if (!endNode) { if (!ts.isArrowFunction(node)) - return; // Function missing parentheses, give up + return false; // Function missing parentheses, give up // If no `)`, is an arrow function `x => x`, so use the end of the first parameter endNode = ts.first(node.parameters); } @@ -119557,6 +120085,7 @@ var ts; endNode = node.kind !== 241 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + return true; }; ChangeTracker.prototype.tryInsertThisTypeAnnotation = function (sourceFile, node, type) { var start = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1; @@ -121183,20 +121712,20 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, formatContext, preferences); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, formatContext, preferences); }); }, }); @@ -121236,7 +121765,7 @@ var ts; } return errorCode; } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, formatContext, preferences) { if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 103 /* ThisKeyword */) { return undefined; } @@ -121247,7 +121776,7 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken, formatContext, preferences); return parent; } if (ts.isPropertyAccessExpression(parent)) { @@ -121264,7 +121793,7 @@ var ts; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken, formatContext, preferences); return symbol.valueDeclaration; } return undefined; @@ -121278,14 +121807,14 @@ var ts; // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken, formatContext, preferences); return param; } return undefined; @@ -121293,14 +121822,14 @@ var ts; case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host, formatContext, preferences); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } return undefined; @@ -121315,12 +121844,12 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken, formatContext, preferences) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host, formatContext, preferences); } } - function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken, formatContext, preferences) { if (!ts.isIdentifier(parameterDeclaration.name)) { return; } @@ -121336,7 +121865,7 @@ var ts; for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; if (declaration && !declaration.type && !declaration.initializer) { - annotate(changes, sourceFile, declaration, type, program, host); + annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences); } } if (needParens) @@ -121365,7 +121894,7 @@ var ts; ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)), ]); } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken, formatContext, preferences) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); @@ -121376,11 +121905,11 @@ var ts; annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); } else { - annotate(changes, sourceFile, param, type, program, host); + annotate(changes, sourceFile, param, type, program, host, formatContext, preferences); } } } - function annotate(changes, sourceFile, declaration, type, program, host) { + function annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (ts.isInJSFile(sourceFile) && declaration.kind !== 157 /* PropertySignature */) { @@ -121392,11 +121921,32 @@ var ts; var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); addJSDocTags(changes, sourceFile, parent, [typeTag]); } - else { + else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences)) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } } } + function tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences) { + var _a; + if (ts.isLiteralImportTypeNode(typeNode) && typeNode.qualifier && type.symbol) { + // Replace 'import("./a").SomeType' with 'SomeType' and an actual import if possible + var moduleSymbol = (_a = ts.find(type.symbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) === null || _a === void 0 ? void 0 : _a.getSourceFile().symbol; + // Symbol for the left-most thing after the dot + if (moduleSymbol) { + var symbol = ts.getFirstIdentifier(typeNode.qualifier).symbol; + var action = codefix.getImportCompletionAction(symbol, moduleSymbol, sourceFile, symbol.name, host, program, formatContext, declaration.pos, preferences); + if (action.codeAction.changes.length && changes.tryInsertTypeAnnotation(sourceFile, declaration, ts.createTypeReferenceNode(typeNode.qualifier, typeNode.typeArguments))) { + for (var _i = 0, _b = action.codeAction.changes; _i < _b.length; _i++) { + var change = _b[_i]; + var file = sourceFile.fileName === change.fileName ? sourceFile : ts.Debug.assertDefined(program.getSourceFile(change.fileName)); + changes.pushRaw(file, change); + } + return true; + } + } + } + return false; + } function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { var signature = parameterInferences.length && parameterInferences[0].declaration.parent; if (!signature) { @@ -122088,7 +122638,7 @@ var ts; } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); } function addCandidateType(usage, type) { if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { @@ -123895,6 +124445,7 @@ var ts; var filteredCount = 0; var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host); var allSourceFiles = program.getSourceFiles(); + var globalTypingsCache = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); forEachExternalModule(program.getTypeChecker(), allSourceFiles, function (module, sourceFile) { if (sourceFile === undefined) { if (!packageJson || packageJson.allowsImportingAmbientModule(module, allSourceFiles)) { @@ -123904,7 +124455,9 @@ var ts; filteredCount++; } } - else if (sourceFile && sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + else if (sourceFile && + sourceFile !== from && + isImportablePath(from.fileName, sourceFile.fileName, ts.hostGetCanonicalFileName(host), globalTypingsCache)) { if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile, allSourceFiles)) { cb(module); } @@ -123934,10 +124487,13 @@ var ts; * Don't include something from a `node_modules` that isn't actually reachable by a global import. * A relative import to node_modules is usually a bad idea. */ - function isImportablePath(fromPath, toPath) { + function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } function moduleSymbolToValidIdentifier(moduleSymbol, target) { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); @@ -123982,6 +124538,7 @@ var ts; readFile: ts.maybeBind(host, host.readFile), useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || program.getProbableSymlinks, + getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), }; var usesNodeCoreModules; return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; @@ -125557,14 +126114,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); - if (sig.hasRestParameter) { + if (ts.signatureHasRestParameter(sig)) { someSigHasRestParameter = true; } - if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!ts.signatureHasRestParameter(sig) || ts.signatureHasRestParameter(maxArgsSignature))) { maxArgsSignature = sig; } } - var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + var maxNonRestArgs = maxArgsSignature.parameters.length - (ts.signatureHasRestParameter(maxArgsSignature) ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { @@ -128049,7 +128606,7 @@ var ts; if (!selection || !ts.isTypeNode(selection)) return undefined; var checker = context.program.getTypeChecker(); - var firstStatement = ts.Debug.assertDefined(isJS ? ts.findAncestor(selection, isStatementAndHasJSDoc) : ts.findAncestor(selection, ts.isStatement), "Should find a statement"); + var firstStatement = ts.Debug.assertDefined(ts.findAncestor(selection, ts.isStatement), "Should find a statement"); var typeParameters = collectTypeParameters(checker, selection, firstStatement, file); if (!typeParameters) return undefined; @@ -128080,9 +128637,6 @@ var ts; } return undefined; } - function isStatementAndHasJSDoc(n) { - return ts.isStatement(n) && ts.hasJSDocNodes(n); - } function rangeContainsSkipTrivia(r1, node, file) { return ts.rangeContainsStartEnd(r1, ts.skipTrivia(file.text, node.pos), node.end); } @@ -130006,8 +130560,9 @@ var ts; return TypeObject; }()); var SignatureObject = /** @class */ (function () { - function SignatureObject(checker) { + function SignatureObject(checker, flags) { this.checker = checker; + this.flags = flags; } SignatureObject.prototype.getDeclaration = function () { return this.declaration; @@ -130045,13 +130600,12 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + ts.forEachUnique(declarations, function (declaration) { var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); - } + }); } return doc; } @@ -130362,9 +130916,7 @@ var ts; names.push(entry); } else { - if (entry.scriptKind !== 6 /* JSON */) { - names.push(entry.hostFileName); - } + names.push(entry.hostFileName); } }); return names; @@ -130932,12 +131484,11 @@ var ts; var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName, emitOnlyDtsFiles) { - if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + return ts.getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit); } // Signature help /** diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 82af4dd532d..444ea34294a 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -81,7 +81,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.7"; + ts.versionMajorMinor = "3.8"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -96,22 +96,32 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; - /** Create a MapLike with good performance. */ - function createDictionaryObject() { - var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - return map; + /** + * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). + */ + function tryGetNativeMap() { + // Internet Explorer's Map doesn't support iteration, so don't use it. + // eslint-disable-next-line no-in-operator + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; } - /** Create a new map. If a template object is provided, the map will copy entries from it. */ + ts.tryGetNativeMap = tryGetNativeMap; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + ts.Map = ts.tryGetNativeMap() || (function () { + // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it. + if (typeof ts.createMapShim === "function") { + return ts.createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); + /** Create a new map. */ function createMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createMap = createMap; + /** Create a new map from an array of entries. */ function createMapFromEntries(entries) { var map = createMap(); for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { @@ -121,8 +131,9 @@ var ts; return map; } ts.createMapFromEntries = createMapFromEntries; + /** Create a new map from a template object is provided, the map will copy entries from it. */ function createMapFromTemplate(template) { - var map = new ts.MapCtr(); + var map = new ts.Map(); // Copies keys/values from template. Note that for..in will not throw if // template is undefined, and instead will just exit the loop. for (var key in template) { @@ -133,147 +144,6 @@ var ts; return map; } ts.createMapFromTemplate = createMapFromTemplate; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // eslint-disable-next-line no-in-operator - ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - // Keep the class inside a function so it doesn't get compiled if it's not used. - function shimMap() { - var MapIterator = /** @class */ (function () { - function MapIterator(currentEntry, selector) { - this.currentEntry = currentEntry; - this.selector = selector; - } - MapIterator.prototype.next = function () { - // Navigate to the next entry. - while (this.currentEntry) { - var skipNext = !!this.currentEntry.skipNext; - this.currentEntry = this.currentEntry.nextEntry; - if (!skipNext) { - break; - } - } - if (this.currentEntry) { - return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false }; - } - else { - return { value: undefined, done: true }; - } - }; - return MapIterator; - }()); - return /** @class */ (function () { - function class_1() { - this.data = createDictionaryObject(); - this.size = 0; - // Create a first (stub) map entry that will not contain a key - // and value but serves as starting point for iterators. - this.firstEntry = {}; - // When the map is empty, the last entry is the same as the - // first one. - this.lastEntry = this.firstEntry; - } - class_1.prototype.get = function (key) { - var entry = this.data[key]; - return entry && entry.value; - }; - class_1.prototype.set = function (key, value) { - if (!this.has(key)) { - this.size++; - // Create a new entry that will be appended at the - // end of the linked list. - var newEntry = { - key: key, - value: value - }; - this.data[key] = newEntry; - // Adjust the references. - var previousLastEntry = this.lastEntry; - previousLastEntry.nextEntry = newEntry; - newEntry.previousEntry = previousLastEntry; - this.lastEntry = newEntry; - } - else { - this.data[key].value = value; - } - return this; - }; - class_1.prototype.has = function (key) { - // eslint-disable-next-line no-in-operator - return key in this.data; - }; - class_1.prototype.delete = function (key) { - if (this.has(key)) { - this.size--; - var entry = this.data[key]; - delete this.data[key]; - // Adjust the linked list references of the neighbor entries. - var previousEntry = entry.previousEntry; - previousEntry.nextEntry = entry.nextEntry; - if (entry.nextEntry) { - entry.nextEntry.previousEntry = previousEntry; - } - // When the deleted entry was the last one, we need to - // adjust the lastEntry reference. - if (this.lastEntry === entry) { - this.lastEntry = previousEntry; - } - // Adjust the forward reference of the deleted entry - // in case an iterator still references it. This allows us - // to throw away the entry, but when an active iterator - // (which points to the current entry) continues, it will - // navigate to the entry that originally came before the - // current one and skip it. - entry.previousEntry = undefined; - entry.nextEntry = previousEntry; - entry.skipNext = true; - return true; - } - return false; - }; - class_1.prototype.clear = function () { - this.data = createDictionaryObject(); - this.size = 0; - // Reset the linked list. Note that we must adjust the forward - // references of the deleted entries to ensure iterators stuck - // in the middle of the list don't continue with deleted entries, - // but can continue with new entries added after the clear() - // operation. - var firstEntry = this.firstEntry; - var currentEntry = firstEntry.nextEntry; - while (currentEntry) { - var nextEntry = currentEntry.nextEntry; - currentEntry.previousEntry = undefined; - currentEntry.nextEntry = firstEntry; - currentEntry.skipNext = true; - currentEntry = nextEntry; - } - firstEntry.nextEntry = undefined; - this.lastEntry = firstEntry; - }; - class_1.prototype.keys = function () { - return new MapIterator(this.firstEntry, function (key) { return key; }); - }; - class_1.prototype.values = function () { - return new MapIterator(this.firstEntry, function (_key, value) { return value; }); - }; - class_1.prototype.entries = function () { - return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; }); - }; - class_1.prototype.forEach = function (action) { - var iterator = this.entries(); - while (true) { - var iterResult = iterator.next(); - if (iterResult.done) { - break; - } - var _a = iterResult.value, key = _a[0], value = _a[1]; - action(value, key); - } - }; - return class_1; - }()); - } - ts.shimMap = shimMap; function length(array) { return array ? array.length : 0; } @@ -1855,20 +1725,6 @@ var ts; return str.indexOf(substring) !== -1; } ts.stringContains = stringContains; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -2182,11 +2038,14 @@ var ts; if (isFlags) { var result = ""; var remainingFlags = value; - for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { - var _a = members[i], enumValue = _a[0], enumName = _a[1]; - if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; + if (enumValue > value) { + break; + } + if (enumValue !== 0 && enumValue & value) { + result = "" + result + (result ? "|" : "") + enumName; remainingFlags &= ~enumValue; - result = "" + enumName + (result ? "|" : "") + result; } } if (remainingFlags === 0) { @@ -2194,8 +2053,8 @@ var ts; } } else { - for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { - var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + for (var _b = 0, members_2 = members; _b < members_2.length; _b++) { + var _c = members_2[_b], enumValue = _c[0], enumName = _c[1]; if (enumValue === value) { return enumName; } @@ -2269,6 +2128,33 @@ var ts; ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; var isDebugInfoEnabled = false; + var extendedDebugModule; + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + Debug.formatControlFlowGraph = formatControlFlowGraph; + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator + Object.defineProperties(flowNode, { + __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } }, + __debugToString: { value: function () { return formatControlFlowGraph(this); } } + }); + } + } + } + Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; /** * Injects debug information into frequently used types. */ @@ -2312,6 +2198,20 @@ var ts; }); } } + // attempt to load extended debugging information + try { + if (ts.sys && ts.sys.require) { + var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath())); + var result = ts.sys.require(basePath, "./compiler-debug"); + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch (_a) { + // do nothing + } isDebugInfoEnabled = true; } Debug.enableDebugInfo = enableDebugInfo; @@ -2475,8 +2375,6 @@ var ts; } /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - var args = typeof process === "undefined" ? [] : process.argv; - ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(args)); })(ts || (ts = {})); /* @internal */ var ts; @@ -3371,6 +3269,7 @@ var ts; /* @internal */ TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + // NOTE: Ensure this is up-to-date with src/debug/debug.ts var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -3426,6 +3325,8 @@ var ts; // When build skipped because passed in project is invalid ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped"; // When build is skipped because project references form cycle + ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ @@ -3435,6 +3336,14 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + /* @internal */ + var ContextFlags; + (function (ContextFlags) { + ContextFlags[ContextFlags["None"] = 0] = "None"; + ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; + ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; + ContextFlags[ContextFlags["Completion"] = 4] = "Completion"; + })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {})); // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { @@ -3837,19 +3746,20 @@ var ts; ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 131072] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 262144] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 524288] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 1048576] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 786432] = "RequiresWidening"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 1835008] = "PropagatingFlags"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -3876,6 +3786,20 @@ var ts; SignatureKind[SignatureKind["Call"] = 0] = "Call"; SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + /* @internal */ + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter"; + SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes"; + SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain"; + SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain"; + // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us + // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when + // instantiating the return type. + SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags"; + SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags"; + })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {})); var IndexKind; (function (IndexKind) { IndexKind[IndexKind["String"] = 0] = "String"; @@ -4876,16 +4800,6 @@ var ts; } } ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; - function recursiveCreateDirectory(directoryPath, sys) { - var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); - if (shouldCreateParent) { - recursiveCreateDirectory(basePath, sys); - } - if (shouldCreateParent || !sys.directoryExists(directoryPath)) { - sys.createDirectory(directoryPath); - } - } /** * patch writefile to create folder before writing the file */ @@ -4894,11 +4808,7 @@ var ts; // patch writefile to create folder before writing the file var originalWriteFile = sys.writeFile; sys.writeFile = function (path, data, writeBom) { - var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); - if (directoryPath && !sys.directoryExists(directoryPath)) { - recursiveCreateDirectory(directoryPath, sys); - } - originalWriteFile.call(sys, path, data, writeBom); + return ts.writeFileEnsuringDirectories(path, data, !!writeBom, function (path, data, writeByteOrderMark) { return originalWriteFile.call(sys, path, data, writeByteOrderMark); }, function (path) { return sys.createDirectory(path); }, function (path) { return sys.directoryExists(path); }); }; } ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory; @@ -5047,6 +4957,15 @@ var ts; bufferFrom: bufferFrom, base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + require: function (baseDir, moduleName) { + try { + var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath: modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error: error }; + } + } }; return nodeSystem; /** @@ -5185,6 +5104,7 @@ var ts; if (fsSupportsRecursive) { return watchDirectoryUsingFsWatch; } + // defer watchDirectoryRecursively as it depends on `ts.createMap()` which may not be usable yet. var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? createWatchDirectoryUsing(fsWatchFile) : tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? @@ -5629,6 +5549,673 @@ var ts; ts.Debug.isDebugging = true; } })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + //// Path Tests + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + //// Path Parsing + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArrays([root], rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + //// Path Formatting + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + //// Path Normalization + /** + * Normalize path separators, converting `\` into `/`. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + //// Path Comparisons + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * @deprecated Use `containsPath` if possible. + */ + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + //// Relative Paths + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArrays([""], relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; +})(ts || (ts = {})); // // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ @@ -5656,7 +6243,7 @@ var ts; An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), - An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), @@ -5864,7 +6451,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd_1323", "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5900,6 +6487,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"), 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), @@ -6027,7 +6615,6 @@ var ts; Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), @@ -6197,8 +6784,8 @@ var ts; JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2610, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_proper_2610", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member property."), - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2611, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_access_2611", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member accessor."), + _0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property: diag(2610, ts.DiagnosticCategory.Error, "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610", "'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property."), + _0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor: diag(2611, ts.DiagnosticCategory.Error, "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611", "'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor."), Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), @@ -6421,6 +7008,8 @@ var ts; Parameter_0_of_accessor_has_or_is_using_private_name_1: diag(4106, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106", "Parameter '{0}' of accessor has or is using private name '{1}'."), Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2: diag(4107, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107", "Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'."), Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4108, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108", "Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named."), + Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), + Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -6428,6 +7017,7 @@ var ts; Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Unknown_compiler_option_0_Did_you_mean_1: diag(5025, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"), Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), @@ -6458,6 +7048,7 @@ var ts; 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}'?"), 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."), @@ -6504,7 +7095,7 @@ var ts; Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has an unsupported extension. The only supported extensions are {1}."), Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), @@ -6712,6 +7303,8 @@ var ts; 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."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), + File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -6815,6 +7408,7 @@ var ts; Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"), + Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"), Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), @@ -9047,7 +9641,7 @@ var ts; ts.getDeclarationOfKind = getDeclarationOfKind; /** Create a new escaped identifier map. */ function createUnderscoreEscapedMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; function hasEntries(map) { @@ -9103,13 +9697,6 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -9916,6 +10503,11 @@ var ts; break; case 201 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); + case 275 /* CaseClause */: + case 276 /* DefaultClause */: + var start = ts.skipTrivia(sourceFile.text, node.pos); + var end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return ts.createTextSpanFromBounds(start, end); } if (errorNode === undefined) { // If we don't have a better node, then just set the error on the first token of @@ -10728,7 +11320,7 @@ var ts; (node.typeArguments[0].kind === 142 /* StringKeyword */ || node.typeArguments[0].kind === 139 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 195 /* CallExpression */) { return false; } @@ -10740,7 +11332,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -10962,27 +11554,31 @@ var ts; isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true); } ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; - function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { - return isLiteralLikeElementAccess(node) - && ((!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */) || - isEntityNameExpression(node.expression) || - isBindableStaticElementAccessExpression(node.expression, /*excludeThisKeyword*/ true)); - } - ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression; + /** x.y OR x[0] */ function isLiteralLikeAccess(node) { return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node); } ts.isLiteralLikeAccess = isLiteralLikeAccess; + /** x[0] OR x['a'] OR x[Symbol.y] */ function isLiteralLikeElementAccess(node) { return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) || isWellKnownSymbolSyntactically(node.argumentExpression)); } ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; + /** Any series of property and element accesses. */ function isBindableStaticAccessExpression(node, excludeThisKeyword) { return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */ || isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; + /** Any series of property and element accesses, ending in a literal element access */ + function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { + return isLiteralLikeElementAccess(node) + && ((!excludeThisKeyword && node.expression.kind === 103 /* ThisKeyword */) || + isEntityNameExpression(node.expression) || + isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true)); + } + ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression; function isBindableStaticNameExpression(node, excludeThisKeyword) { return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword); } @@ -11011,7 +11607,7 @@ var ts; if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) { return 0 /* None */; } - if (isBindableStaticNameExpression(expr.left.expression) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { // F.prototype = { ... } return 6 /* Prototype */; } @@ -11067,13 +11663,17 @@ var ts; nextToLast = nextToLast.expression; } var id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { - // exports.name = expr OR module.exports.name = expr + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + // ExportsProperty does not support binding with computed names + isBindableStaticAccessExpression(lhs)) { + // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return 1 /* ExportsProperty */; } - // F.G...x = expr - return 5 /* Property */; + if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs) && lhs.expression.kind !== 103 /* ThisKeyword */)) { + // F.G...x = expr + return 5 /* Property */; + } } return 0 /* None */; } @@ -12395,7 +12995,7 @@ var ts; */ function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); var extensionless = ts.removeFileExtension(relativePath); @@ -12478,6 +13078,25 @@ var ts; }, sourceFiles); } ts.writeFile = writeFile; + function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists); + createDirectory(directoryPath); + } + } + function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) { + // PERF: Checking for directory existence is expensive. Instead, assume the directory exists + // and fall back to creating it if the file write fails. + try { + writeFile(path, data, writeByteOrderMark); + } + catch (_a) { + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists); + writeFile(path, data, writeByteOrderMark); + } + } + ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories; function getLineOfLocalPosition(currentSourceFile, pos) { return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; } @@ -12917,6 +13536,23 @@ var ts; return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function getFirstIdentifier(node) { + switch (node.kind) { + case 75 /* Identifier */: + return node; + case 152 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 75 /* Identifier */); + return node; + case 193 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 75 /* Identifier */); + return node; + } + } + ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { return node.kind === 75 /* Identifier */ || node.kind === 103 /* ThisKeyword */ || node.kind === 193 /* PropertyAccessExpression */ && isDottedName(node.expression) || @@ -13435,20 +14071,6 @@ var ts; }); } ts.mutateMap = mutateMap; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); @@ -13475,7 +14097,7 @@ var ts; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { @@ -14540,11 +15162,47 @@ var ts; } ts.isCallChain = isCallChain; function isOptionalChain(node) { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + var kind = node.kind; + return !!(node.flags & 32 /* OptionalChain */) && + (kind === 193 /* PropertyAccessExpression */ + || kind === 194 /* ElementAccessExpression */ + || kind === 195 /* CallExpression */); } ts.isOptionalChain = isOptionalChain; + /* @internal */ + function isOptionalChainRoot(node) { + return isOptionalChain(node) && !!node.questionDotToken; + } + ts.isOptionalChainRoot = isOptionalChainRoot; + /** + * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`). + */ + /* @internal */ + function isExpressionOfOptionalChainRoot(node) { + return isOptionalChainRoot(node.parent) && node.parent.expression === node; + } + ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot; + /** + * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`: + * + * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`) + * 2. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain) + * 3. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is + * the end of the chain starting at `c?.`) + * 4. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is + * the end of the chain starting at `a?.`) + */ + /* @internal */ + function isOutermostOptionalChain(node) { + return !isOptionalChain(node.parent) // cases 1 and 2 + || isOptionalChainRoot(node.parent) // case 3 + || node !== node.parent.expression; // case 4 + } + ts.isOutermostOptionalChain = isOutermostOptionalChain; + function isNullishCoalesce(node) { + return node.kind === 208 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; + } + ts.isNullishCoalesce = isNullishCoalesce; function isNewExpression(node) { return node.kind === 196 /* NewExpression */; } @@ -15815,11 +16473,6 @@ var ts; return node.kind === 162 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; - /* @internal */ - function isOptionalChainRoot(node) { - return ts.isOptionalChain(node) && !!node.questionDotToken; - } - ts.isOptionalChainRoot = isOptionalChainRoot; /** True if has jsdoc nodes attached to it. */ /* @internal */ // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times @@ -15906,7 +16559,12 @@ var ts; this.checker = checker; } } - function Signature() { } + function Signature(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } function Node(kind, pos, end) { this.pos = pos; this.end = end; @@ -16181,273 +16839,6 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - /** - * Normalize path separators. - */ - function normalizeSlashes(path) { - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - function isVolumeCharacter(charCode) { - return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || - (charCode >= 65 /* A */ && charCode <= 90 /* Z */); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; - if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; - } - return -1; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - // POSIX or UNC - if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; // POSIX: "/" (or non-normalized "\") - var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; // UNC: "//server" or "\\server" - return p1 + 1; // UNC: "//server/" or "\\server\" - } - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) - return 2; // DOS: "c:" (but not "c:d") - } - // URL - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - // relative - return 0; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - // TODO(rbuckton): replace references with `resolvePath` - function normalizePath(path) { - return ts.resolvePath(path); - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - // If the path provided is itself the root, then return it. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = ts.removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - /** - * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArrays([root], rest); - } - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = ts.combinePaths(currentDirectory, path); - var rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - ts.getPathComponents = getPathComponents; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - */ - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var result = ts.createMap(); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { @@ -16464,15 +16855,15 @@ var ts; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { aParts.pop(); bParts.pop(); } - return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; } // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. @@ -16482,229 +16873,8 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); - var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArrays([""], relative, components); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - */ - function ensurePathIsNonModuleName(path) { - return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function getBaseFileName(path, extensions, ignoreCase) { - path = ts.normalizeSlashes(path); - // if the path provided is itself the root, then it has not file name. - var rootLength = ts.getRootLength(path); - if (rootLength === path.length) - return ""; - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - /** - * Combines paths. If a path is absolute, it replaces any previous path. - */ - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = ts.normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = ts.normalizeSlashes(relativePath); - if (!path || ts.getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. - */ - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - var combined = ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : ts.normalizeSlashes(path); - var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.resolvePath = resolvePath; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path) { - if (path.length === 0) - return false; - var ch = path.charCodeAt(path.length - 1); - return ch === 47 /* slash */ || ch === 92 /* backslash */; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - // check path for these segments: '', '.'. '..' - var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - var aRoot = a.substring(0, ts.getRootLength(a)); - var bRoot = b.substring(0, ts.getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0 /* EqualTo */) { - return result; - } - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); - var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_1 = componentComparer(aComponents[i], bComponents[i]); - if (result_1 !== 0 /* EqualTo */) { - return result_1; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - /** - * Performs a case-sensitive comparison of two paths. - */ - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); - var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function isDirectorySeparator(charCode) { - return charCode === 47 /* slash */ || charCode === 92 /* backslash */; - } function stripLeadingDirectorySeparator(s) { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); @@ -16723,10 +16893,6 @@ var ts; return "\\" + match; } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -16802,7 +16968,7 @@ var ts; } // getNormalizedPathComponents includes the separator for the root component. // We need to remove to create our regex correctly. - components[0] = removeTrailingDirectorySeparator(components[0]); + components[0] = ts.removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); } @@ -16864,7 +17030,7 @@ var ts; function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); + var absolutePath = ts.combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), @@ -16893,7 +17059,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -16903,8 +17069,8 @@ var ts; visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) @@ -16931,8 +17097,8 @@ var ts; } for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { visitDirectory(name, absoluteName, depth); @@ -16954,14 +17120,14 @@ var ts; var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") - var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include)); // Append the literal and canonical candidate base paths. includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -16978,9 +17144,9 @@ var ts; var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { // No "*" or "?" in the path - return !hasExtension(absolute) + return !ts.hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -17052,10 +17218,6 @@ var ts; return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJSFileExtension = hasJSFileExtension; - function hasJSOrJsonFileExtension(fileName) { - return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); - } - ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; function hasTSFileExtension(fileName) { return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -17145,14 +17307,9 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); @@ -17195,36 +17352,6 @@ var ts; return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") - extensions = [extensions]; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -18432,6 +18559,9 @@ var ts; function doInYieldAndAwaitContext(func) { return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func); } + function doOutsideOfYieldAndAwaitContext(func) { + return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func); + } function inContext(flags) { return (contextFlags & flags) !== 0; } @@ -22703,18 +22833,7 @@ var ts; node.exclamationToken = parseTokenNode(); } node.type = parseTypeAnnotation(); - // For instance properties specifically, since they are evaluated inside the constructor, - // we do *not * want to parse yield expressions, so we specifically turn the yield context - // off. The grammar would look something like this: - // - // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; - // - // The checker may still error in the static case to explicitly disallow the yield expression. - node.initializer = ts.hasModifier(node, 32 /* Static */) - ? allowInAnd(parseInitializer) - : doOutsideOfContext(8192 /* YieldContext */ | 4096 /* DisallowInContext */, parseInitializer); + node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer); parseSemicolon(); return finishNode(node); } @@ -23005,7 +23124,7 @@ var ts; parseExpected(87 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(18 /* OpenBraceToken */)) { - node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); }); parseExpected(19 /* CloseBraceToken */); } else { @@ -25067,6 +25186,15 @@ var ts; isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, // Basic { name: "target", @@ -25898,8 +26026,7 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { - var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; + function parseCommandLineWorker(getOptionNameMap, diagnostics, commandLine, readFile) { var options = {}; var fileNames = []; var errors = []; @@ -25926,7 +26053,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); + errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -25962,7 +26089,13 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); + var possibleOption = ts.getSpellingSuggestion(s, ts.optionDeclarations, function (opt) { return "--" + opt.name; }); + if (possibleOption) { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownDidYouMeanDiagnostic, s, possibleOption.name)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownOptionDiagnostic, s)); + } } } else { @@ -26005,11 +26138,13 @@ var ts; parseStrings(args); } } + var compilerOptionsDefaultDiagnostics = { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument + }; function parseCommandLine(commandLine, readFile) { - return parseCommandLineWorker(getOptionNameMap, [ - ts.Diagnostics.Unknown_compiler_option_0, - ts.Diagnostics.Compiler_option_0_expects_an_argument - ], commandLine, readFile); + return parseCommandLineWorker(getOptionNameMap, compilerOptionsDefaultDiagnostics, commandLine, readFile); } ts.parseCommandLine = parseCommandLine; /** @internal */ @@ -26034,10 +26169,11 @@ var ts; function parseBuildCommand(args) { var buildOptionNameMap; var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; - var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ - ts.Diagnostics.Unknown_build_option_0, - ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 - ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + }, args), options = _a.options, projects = _a.fileNames, errors = _a.errors; var buildOptions = options; if (projects.length === 0) { // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." @@ -26059,6 +26195,7 @@ var ts; return { buildOptions: buildOptions, projects: projects, errors: errors }; } ts.parseBuildCommand = parseBuildCommand; + /* @internal */ function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -26067,104 +26204,7 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - /* @internal */ - function printVersion() { - ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); - } - ts.printVersion = printVersion; - /* @internal */ - function printHelp(optionsList, syntaxPrefix) { - if (syntaxPrefix === void 0) { syntaxPrefix = ""; } - var output = []; - // We want to align our "syntax" and "examples" commands to a certain margin. - var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); - // Build up the syntactic skeleton. - var syntax = makePadding(marginLength - syntaxLength); - syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; - output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); - output.push(ts.sys.newLine + ts.sys.newLine); - // Build up the list of examples. - var padding = makePadding(marginLength); - output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); - output.push(padding + "tsc @args.txt" + ts.sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); - output.push(ts.sys.newLine); - output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); - // We want our descriptions to align at the same column in our output, - // so we keep track of the longest option usage string. - marginLength = 0; - var usageColumn = []; // Things like "-d, --declaration" go in here. - var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind - for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { - var option = optionsList_1[_i]; - // If an option lacks a description, - // it is not officially supported. - if (!option.description) { - continue; - } - var usageText_1 = " "; - if (option.shortName) { - usageText_1 += "-" + option.shortName; - usageText_1 += getParamType(option); - usageText_1 += ", "; - } - usageText_1 += "--" + option.name; - usageText_1 += getParamType(option); - usageColumn.push(usageText_1); - var description = void 0; - if (option.name === "lib") { - description = getDiagnosticText(option.description); - var element = option.element; - var typeMap = element.type; - optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); - } - else { - description = getDiagnosticText(option.description); - } - descriptionColumn.push(description); - // Set the new margin for the description column if necessary. - marginLength = Math.max(usageText_1.length, marginLength); - } - // Special case that can't fit in the loop. - var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; - var kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { - var kind = kindsList_1[_a]; - output.push(kind + " "); - } - output.push(ts.sys.newLine); - } - } - for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { - var line = output_1[_b]; - ts.sys.write(line); - } - return; - function getParamType(option) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - } - ts.printHelp = printHelp; + ts.getDiagnosticText = getDiagnosticText; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -26248,19 +26288,28 @@ var ts; name: "compilerOptions", type: "object", elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1 + }, }, { name: "typingOptions", type: "object", elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 + }, }, { name: "typeAcquisition", type: "object", elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + extraKeyDiagnostics: { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 + } }, { name: "extends", @@ -26325,7 +26374,7 @@ var ts; function isRootOptionMap(knownOptions) { return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } - function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; @@ -26342,8 +26391,19 @@ var ts; var textOfKey = ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; - if (keyText && extraKeyDiagnosticMessage && !option) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + if (keyText && extraKeyDiagnostics && !option) { + if (knownOptions) { + var possibleOption = ts.getSpellingSuggestion(keyText, ts.arrayFrom(knownOptions.keys()), ts.identity); + if (possibleOption) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownDidYouMeanDiagnostic, keyText, possibleOption)); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } } var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { @@ -26427,8 +26487,8 @@ var ts; // vs what we set in the json // If need arises, we can modify this interface and callbacks as needed if (option) { - var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; - return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName); } else { return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, @@ -26483,7 +26543,7 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign(__assign({ compilerOptions: __assign(__assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; @@ -26504,12 +26564,12 @@ var ts; return undefined; return specs; } - function matchesSpecs(path, includeSpecs, excludeSpecs) { + function matchesSpecs(path, includeSpecs, excludeSpecs, host) { if (!includeSpecs) return function (_) { return true; }; - var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); - var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); - var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; @@ -26686,6 +26746,35 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + /* @internal */ + function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + var result = {}; + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name in options) { + if (ts.hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; + function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option) { + if (option.type === "list") { + var values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value); + } + } + return value; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -27074,7 +27163,7 @@ var ts; } function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); - convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, compilerOptionsDefaultDiagnostics, errors); if (configFileName) { options.configFilePath = ts.normalizeSlashes(configFileName); } @@ -27086,10 +27175,14 @@ var ts; function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); - convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + var diagnostics = { + unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1, + }; + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, diagnostics, errors); return options; } - function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnostics, errors) { if (!jsonOptions) { return; } @@ -27100,7 +27193,13 @@ var ts; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } else { - errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + var possibleOption = ts.getSpellingSuggestion(id, optionDeclarations, function (opt) { return opt.name; }); + if (possibleOption) { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownDidYouMeanDiagnostic, id, possibleOption.name)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostics.unknownOptionDiagnostic, id)); + } } } } @@ -27136,7 +27235,7 @@ var ts; } function normalizeNonListOptionValue(option, basePath, value) { if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + value = ts.getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } @@ -28920,7 +29019,10 @@ var ts; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); - var flowNodeCreated = ts.identity; + function initFlowNode(node) { + ts.Debug.attachFlowNodeDebugInfo(node); + return node; + } var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -28949,6 +29051,7 @@ var ts; var currentReturnTarget; var currentTrueTarget; var currentFalseTarget; + var currentExceptionTarget; var preSwitchCaseFlow; var activeLabels; var hasExplicitReturn; @@ -28984,6 +29087,9 @@ var ts; symbolCount = 0; skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); + // Attach debugging information if necessary + ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); + ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -29006,6 +29112,7 @@ var ts; currentReturnTarget = undefined; currentTrueTarget = undefined; currentFalseTarget = undefined; + currentExceptionTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; emitFlags = 0 /* None */; @@ -29327,11 +29434,11 @@ var ts; blockScopeContainer.locals = undefined; } if (containerFlags & 4 /* IsControlFlowContainer */) { - var saveFlowNodeCreated = flowNodeCreated; var saveCurrentFlow = currentFlow; var saveBreakTarget = currentBreakTarget; var saveContinueTarget = currentContinueTarget; var saveReturnTarget = currentReturnTarget; + var saveExceptionTarget = currentExceptionTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && @@ -29339,7 +29446,7 @@ var ts; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isIIFE) { - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.node = node; } @@ -29347,11 +29454,11 @@ var ts; // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. currentReturnTarget = isIIFE || node.kind === 161 /* Constructor */ ? createBranchLabel() : undefined; + currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = ts.identity; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~2816 /* ReachabilityAndEmitFlags */; @@ -29377,9 +29484,9 @@ var ts; currentBreakTarget = saveBreakTarget; currentContinueTarget = saveContinueTarget; currentReturnTarget = saveReturnTarget; + currentExceptionTarget = saveExceptionTarget; activeLabels = saveActiveLabels; hasExplicitReturn = saveHasExplicitReturn; - flowNodeCreated = saveFlowNodeCreated; } else if (containerFlags & 64 /* IsInterface */) { seenThisKeyword = false; @@ -29520,9 +29627,6 @@ var ts; case 309 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; - case 307 /* JSDocClassTag */: - bindJSDocClassTag(node); - break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 288 /* SourceFile */: { bindEachFunctionsFirst(node.statements); @@ -29562,9 +29666,8 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 103 /* ThisKeyword */ || expr.kind === 101 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && - ts.isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + ts.isOptionalChain(expr); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -29621,10 +29724,10 @@ var ts; return isNarrowableReference(expr); } function createBranchLabel() { - return { flags: 4 /* BranchLabel */, antecedents: undefined }; + return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); } function createLoopLabel() { - return { flags: 8 /* LoopLabel */, antecedents: undefined }; + return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined }); } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag @@ -29643,36 +29746,32 @@ var ts; if (!expression) { return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - if (!ts.isOptionalChainRoot(expression.parent)) { - return unreachableFlow; - } + if ((expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) && + !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) { + return unreachableFlow; } if (!isNarrowingExpression(expression)) { return antecedent; } setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: flags, antecedent: antecedent, node: expression }); + return initFlowNode({ flags: flags, antecedent: antecedent, node: expression }); } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { - return antecedent; - } setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd }); + return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd }); } - function createFlowAssignment(antecedent, node) { + function createFlowMutation(flags, antecedent, node) { setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 16 /* Assignment */, antecedent: antecedent, node: node }); + var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node }); + if (currentExceptionTarget) { + addAntecedent(currentExceptionTarget, result); + } + return result; } function createFlowCall(antecedent, node) { setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 512 /* Call */, antecedent: antecedent, node: node }); - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - return flowNodeCreated({ flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }); + return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node }); } function finishFlowLabel(flow) { var antecedents = flow.antecedents; @@ -29732,7 +29831,7 @@ var ts; } function bindCondition(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); - if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && isOutermostOptionalChain(node))) { + if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -29863,87 +29962,56 @@ var ts; } function bindTryStatement(node) { var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - var tryPriors = []; - var oldFlowNodeCreated = flowNodeCreated; - // We hook the creation of all flow nodes within the `try` scope and store them so we can add _all_ of them - // as possible antecedents of the start of the `catch` or `finally` blocks. - // Don't bother intercepting the call if there's no finally or catch block that needs the information - if (node.catchClause || node.finallyBlock) { - flowNodeCreated = function (node) { return (tryPriors.push(node), node); }; - } + // We conservatively assume that *any* code in the try block can cause an exception, but we only need + // to track code that causes mutations (because only mutations widen the possible control flow type of + // a variable). The currentExceptionTarget is the target label for control flows that result from + // exceptions. We add all mutation flow nodes as antecedents of this label such that we can analyze them + // as possible antecedents of the start of catch or finally blocks. Furthermore, we add the current + // control flow to represent exceptions that occur before any mutations. + var saveExceptionTarget = currentExceptionTarget; + currentExceptionTarget = createBranchLabel(); + addAntecedent(currentExceptionTarget, currentFlow); bind(node.tryBlock); - flowNodeCreated = oldFlowNodeCreated; addAntecedent(preFinallyLabel, currentFlow); var flowAfterTry = currentFlow; var flowAfterCatch = unreachableFlow; if (node.catchClause) { - currentFlow = preTryFlow; - if (tryPriors.length) { - var preCatchFlow = createBranchLabel(); - addAntecedent(preCatchFlow, currentFlow); - for (var _i = 0, tryPriors_1 = tryPriors; _i < tryPriors_1.length; _i++) { - var p = tryPriors_1[_i]; - addAntecedent(preCatchFlow, p); - } - currentFlow = finishFlowLabel(preCatchFlow); - } + // Start of catch clause is the target of exceptions from try block. + currentFlow = finishFlowLabel(currentExceptionTarget); + // The currentExceptionTarget now represents control flows from exceptions in the catch clause. + // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block + // acts like a second try block. + currentExceptionTarget = createBranchLabel(); + addAntecedent(currentExceptionTarget, currentFlow); bind(node.catchClause); addAntecedent(preFinallyLabel, currentFlow); flowAfterCatch = currentFlow; } + var exceptionTarget = finishFlowLabel(currentExceptionTarget); + currentExceptionTarget = saveExceptionTarget; if (node.finallyBlock) { - // We add the nodes within the `try` block to the `finally`'s antecedents if there's no catch block - // (If there is a `catch` block, it will have all these antecedents instead, and the `finally` will - // have the end of the `try` block and the end of the `catch` block) - var preFinallyPrior = preTryFlow; - if (!node.catchClause) { - if (tryPriors.length) { - var preFinallyFlow_1 = createBranchLabel(); - addAntecedent(preFinallyFlow_1, preTryFlow); - for (var _a = 0, tryPriors_2 = tryPriors; _a < tryPriors_2.length; _a++) { - var p = tryPriors_2[_a]; - addAntecedent(preFinallyFlow_1, p); - } - preFinallyPrior = finishFlowLabel(preFinallyFlow_1); - } - } - // in finally flow is combined from pre-try/flow from try/flow from catch - // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable - // also for finally blocks we inject two extra edges into the flow graph. - // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it - // second -> edge that represents post-finally flow. - // these edges are used in following scenario: - // let a; (1) - // try { a = someOperation(); (2)} - // finally { (3) console.log(a) } (4) - // (5) a - // flow graph for this case looks roughly like this (arrows show ): - // (1-pre-try-flow) <--.. <-- (2-post-try-flow) - // ^ ^ - // |*****(3-pre-finally-label) -----| - // ^ - // |-- ... <-- (4-post-finally-label) <--- (5) - // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account - // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) - // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable - // Simply speaking code inside finally block is treated as reachable as pre-try-flow - // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. - // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from - // final flows of these blocks without taking pre-try flow into account. - // - // extra edges that we inject allows to control this behavior - // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }; + // Possible ways control can reach the finally block: + // 1) Normal completion of try block of a try-finally or try-catch-finally + // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally + // 3) Exception in try block of a try-finally + // 4) Exception in catch block of a try-catch-finally + // When analyzing a control flow graph that starts inside a finally block we want to consider all + // four possibilities above. However, when analyzing a control flow graph that starts outside (past) + // the finally block, we only want to consider the first two (if we're past a finally block then it + // must have completed normally). To make this possible, we inject two extra nodes into the control + // flow graph: An after-finally with an antecedent of the control flow at the end of the finally + // block, and a pre-finally with an antecedent that represents all exceptional control flows. The + // 'lock' property of the pre-finally references the after-finally, and the after-finally has a + // boolean 'locked' property that we set to true when analyzing a control flow that contained the + // the after-finally node. When the lock associated with a pre-finally is locked, the antecedent of + // the pre-finally (i.e. the exceptional control flows) are skipped. + var preFinallyFlow = initFlowNode({ flags: 4096 /* PreFinally */, antecedent: exceptionTarget, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); - // if flow after finally is unreachable - keep it - // otherwise check if flows after try and after catch are unreachable - // if yes - convert current flow to unreachable - // i.e. - // try { return "1" } finally { console.log(1); } - // console.log(2); // this line should be unreachable even if flow falls out of finally block + // If the end of the finally block is reachable, but the end of the try and catch blocks are not, + // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should + // result in an unreachable current control flow. if (!(currentFlow.flags & 1 /* Unreachable */)) { if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow @@ -29952,7 +30020,7 @@ var ts; } } if (!(currentFlow.flags & 1 /* Unreachable */)) { - var afterFinallyFlow = flowNodeCreated({ flags: 8192 /* AfterFinally */, antecedent: currentFlow }); + var afterFinallyFlow = initFlowNode({ flags: 8192 /* AfterFinally */, antecedent: currentFlow }); preFinallyFlow.lock = afterFinallyFlow; currentFlow = afterFinallyFlow; } @@ -29986,6 +30054,7 @@ var ts; var savedSubtreeTransformFlags = subtreeTransformFlags; subtreeTransformFlags = 0; var clauses = node.clauses; + var isNarrowingSwitch = isNarrowingExpression(node.parent.expression); var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { var clauseStart = i; @@ -29994,14 +30063,14 @@ var ts; i++; } var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; @@ -30065,7 +30134,7 @@ var ts; } function bindAssignmentTargetFlow(node) { if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); + currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } else if (node.kind === 191 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { @@ -30146,7 +30215,7 @@ var ts; if (operator === 62 /* EqualsToken */ && node.left.kind === 194 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } } @@ -30182,7 +30251,7 @@ var ts; } } else { - currentFlow = createFlowAssignment(currentFlow, node); + currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } } function bindVariableDeclarationFlow(node) { @@ -30204,12 +30273,9 @@ var ts; addDeclarationToSymbol(host.symbol, host, 32 /* Class */); } } - function isOutermostOptionalChain(node) { - return !ts.isOptionalChain(node.parent) || ts.isOptionalChainRoot(node.parent) || node !== node.parent.expression; - } function bindOptionalExpression(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); - if (!ts.isOptionalChain(node) || isOutermostOptionalChain(node)) { + if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -30247,7 +30313,7 @@ var ts; currentFlow = finishFlowLabel(preChainLabel); } doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget); - if (isOutermostOptionalChain(node)) { + if (ts.isOutermostOptionalChain(node)) { addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } @@ -30291,7 +30357,7 @@ var ts; if (node.expression.kind === 193 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } } @@ -30591,7 +30657,7 @@ var ts; var host = ts.getJSDocHost(typeAlias); container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); var declName = ts.getNameOfDeclaration(typeAlias); @@ -30604,7 +30670,12 @@ var ts; switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: - container = file; + if (!ts.isExternalOrCommonJsModule(file)) { + container = undefined; + } + else { + container = file; + } break; case 4 /* ThisProperty */: container = declName.parent.expression; @@ -30618,7 +30689,9 @@ var ts; case 0 /* None */: return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration"); } - declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + if (container) { + declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + } container = oldContainer; } } @@ -31014,6 +31087,8 @@ var ts; case 302 /* JSDocTypeLiteral */: case 185 /* MappedType */: return bindAnonymousTypeWorker(node); + case 307 /* JSDocClassTag */: + return bindJSDocClassTag(node); case 192 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); case 200 /* FunctionExpression */: @@ -31233,7 +31308,8 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -31249,7 +31325,7 @@ var ts; constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); } } - if (constructorSymbol) { + if (constructorSymbol && constructorSymbol.valueDeclaration) { // Declare a 'member' if the container is an ES5 class or ES6 constructor constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); // It's acceptable for multiple 'this' assignments of the same identifier to occur @@ -31322,6 +31398,10 @@ var ts; } function bindObjectDefinePrototypeProperty(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol) { + // Ensure the namespace symbol becomes class-like + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** @@ -31396,7 +31476,7 @@ var ts; } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); } return namespaceSymbol; @@ -32045,7 +32125,8 @@ var ts; || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type - || !node.body) { + || !node.body + || node.questionToken) { transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax @@ -32082,7 +32163,7 @@ var ts; function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 1048576 /* ContainsClassFields */; // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax. - if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type) { + if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken) { transformFlags |= 1 /* AssertTypeScript */; } // Hoisted variables related to class properties should live within the TypeScript class wrapper. @@ -32887,6 +32968,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 7] = "ResolvedTypeArguments"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -32897,12 +32979,6 @@ var ts; CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; })(CheckMode || (CheckMode = {})); - var ContextFlags; - (function (ContextFlags) { - ContextFlags[ContextFlags["None"] = 0] = "None"; - ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; - ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; - })(ContextFlags || (ContextFlags = {})); var AccessFlags; (function (AccessFlags) { AccessFlags[AccessFlags["None"] = 0] = "None"; @@ -33036,14 +33112,12 @@ var ts; undefinedSymbol.declarations = []; var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); globalThisSymbol.exports = globals; + globalThisSymbol.declarations = []; globals.set(globalThisSymbol.escapedName, globalThisSymbol); var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; - // This object is reused for `checkOptionalExpression` return values to avoid frequent GC due to nursery object allocations. - // This object represents a pool-size of 1. - var pooledOptionalTypeResult = { isOptional: false, type: undefined }; // for public members that accept a Node or one of its subtypes, we must guard against // synthetic nodes created during transformations by calling `getParseTreeNode`. // for most of these, we perform the guard only on `checker` to avoid any possible @@ -33162,9 +33236,9 @@ var ts; }, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (nodeIn) { + getContextualType: function (nodeIn, contextFlags) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); @@ -33213,7 +33287,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments), getAmbientModules: getAmbientModules, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { @@ -33342,10 +33416,10 @@ var ts; var errorType = createIntrinsicType(1 /* Any */, "error"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 262144 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 262144 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -33371,7 +33445,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", 1048576 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -33389,7 +33463,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 |= 1048576 /* NonInferrableType */; + anyFunctionType.objectFlags |= 2097152 /* 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); @@ -33398,10 +33472,10 @@ var ts; markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances var noIterationTypes = { @@ -33554,7 +33628,7 @@ var ts; var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } } } @@ -33564,7 +33638,7 @@ var ts; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -35042,7 +35116,7 @@ var ts; var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0); var symbol; if (name.kind === 75 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { @@ -35154,7 +35228,12 @@ var ts; return undefined; } var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl); - return init && getSymbolOfNode(init) || undefined; + if (init) { + var initSymbol = getSymbolOfNode(init); + if (initSymbol) { + return mergeJSSymbols(initSymbol, symbol); + } + } } function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); @@ -35581,8 +35660,8 @@ var ts; } function findConstructorDeclaration(node) { var members = node.members; - for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { - var member = members_2[_i]; + for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { + var member = members_3[_i]; if (member.kind === 161 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } @@ -36005,7 +36084,7 @@ var ts; // Type Reference or TypeAlias entity = Identifier meaning = 788968 /* Type */; } - var firstIdentifier = getFirstIdentifier(entityName); + var firstIdentifier = ts.getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { @@ -36497,8 +36576,6 @@ var ts; else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && ts.isClassLike(type.symbol.valueDeclaration) && - // Use `import` types for refs to other scopes, only anonymize something defined in the same scope - ts.findAncestor(type.symbol.valueDeclaration, function (d) { return d === ts.getSourceFileOfNode(context.enclosingDeclaration); }) && !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } @@ -36659,9 +36736,9 @@ var ts; } } } - var propertyName = symbolToName(propertySymbol, context, 111551 /* Value */, /*expectsIdentifier*/ true); - context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; + var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */); @@ -36860,7 +36937,7 @@ var ts; if (!context.tracker.trackSymbol) return; // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(accessExpression); + var firstIdentifier = ts.getFirstIdentifier(accessExpression); var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */); @@ -37226,22 +37303,34 @@ var ts; } } } + function isSingleQuotedStringNamed(d) { + var name = ts.getNameOfDeclaration(d); + if (name && ts.isStringLiteral(name) && (name.singleQuote || + (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")))) { + return true; + } + return false; + } function getPropertyNameNodeForSymbol(symbol, context) { - var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context); + var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed); + var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote); if (fromNameType) { return fromNameType; } + if (ts.isKnownSymbol(symbol)) { + return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3))); + } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); - return createPropertyNameNodeForIdentifierOrLiteral(rawName); + return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote); } // See getNameForSymbolFromNameType for a stringy equivalent - function getPropertyNameNodeForSymbolFromNameType(symbol, context) { + function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) { var nameType = symbol.nameType; if (nameType) { if (nameType.flags & 384 /* StringOrNumberLiteral */) { var name = "" + nameType.value; if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { - return ts.createLiteral(name); + return ts.createLiteral(name, !!singleQuote); } if (isNumericLiteralName(name) && ts.startsWith(name, "-")) { return ts.createComputedPropertyName(ts.createLiteral(+name)); @@ -37253,8 +37342,8 @@ var ts; } } } - function createPropertyNameNodeForIdentifierOrLiteral(name) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name); + function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -37294,7 +37383,7 @@ var ts; var visitedSymbols = ts.createMap(); var deferredPrivates; var oldcontext = context; - context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.mapMap(symbolTable, function (_symbol, name) { return [ts.unescapeLeadingUnderscores(name), true]; }), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { + context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it @@ -37312,6 +37401,10 @@ var ts; context.usedSymbolNames.set(name, true); }); } + ts.forEachEntry(symbolTable, function (symbol, name) { + var baseName = ts.unescapeLeadingUnderscores(name); + void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames` + }); var addingDeclare = !bundled; var exportEquals = symbolTable.get("export=" /* ExportEquals */); if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) { @@ -37503,7 +37596,11 @@ var ts; isPrivate = true; } var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0); - if (symbol.flags & 16 /* Function */) { + var isConstMergedWithNS = symbol.flags & 1536 /* Module */ && + symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && + symbol.escapedName !== "export=" /* ExportEquals */; + var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol); + if (symbol.flags & 16 /* Function */ || isConstMergedWithNSPrintableAsSignatureMerge) { serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } if (symbol.flags & 524288 /* TypeAlias */) { @@ -37514,7 +37611,8 @@ var ts; if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) - && !(symbol.flags & 32 /* Class */)) { + && !(symbol.flags & 32 /* Class */) + && !isConstMergedWithNSPrintableAsSignatureMerge) { serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags); } if (symbol.flags & 384 /* Enum */) { @@ -37531,7 +37629,7 @@ var ts; serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } } - if (symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */)) { + if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) { serializeModule(symbol, symbolName, modifierFlags); } if (symbol.flags & 64 /* Interface */) { @@ -37559,7 +37657,10 @@ var ts; } } function includePrivateSymbol(symbol) { + if (ts.some(symbol.declarations, ts.isParameterDeclaration)) + return; ts.Debug.assertDefined(deferredPrivates); + getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol deferredPrivates.set("" + getSymbolId(symbol), symbol); } function isExportingScope(enclosingDeclaration) { @@ -37618,8 +37719,14 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } + function getNamespaceMembersForSerialization(symbol) { + return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + } + function isTypeOnlyNamespace(symbol) { + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); }); + } function serializeModule(symbol, symbolName, modifierFlags) { - var members = !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + var members = getNamespaceMembersForSerialization(symbol); // Split NS members up by declaration - members whose parent symbol is the ns symbol vs those whose is not (but were added in later via merging) var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; }); var realMembers = locationMap.get("real") || ts.emptyArray; @@ -37629,17 +37736,20 @@ var ts; // so we don't even have placeholders to fill in. if (ts.length(realMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, /*suppressNewPrivateContext*/ false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); } if (ts.length(mergedMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - ts.forEach(mergedMembers, includePrivateSymbol); var nsBody = ts.createModuleBlock([ts.createExportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); - return ts.createExportSpecifier(name === localName ? undefined : localName, name); + var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); + includePrivateSymbol(target || s); + var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; + return ts.createExportSpecifier(name === targetName ? undefined : targetName, name); })))]); addResult(ts.createModuleDeclaration( /*decorators*/ undefined, @@ -37840,7 +37950,11 @@ var ts; case 254 /* ImportClause */: addResult(ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), + // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned + // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag + // In such cases, the `target` refers to the module itself already + ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 255 /* NamespaceImport */: addResult(ts.createImportDeclaration( @@ -37852,7 +37966,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([ ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName)) - ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 261 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, @@ -37866,6 +37980,7 @@ var ts; serializeMaybeAliasAssignment(symbol); break; case 208 /* BinaryExpression */: + case 193 /* PropertyAccessExpression */: // Could be best encoded as though an export specifier or as though an export assignment // If name is default or export=, do an export assignment // Otherwise do an export specifier @@ -37876,10 +37991,6 @@ var ts; serializeExportSpecifier(localName, targetName); } break; - case 193 /* PropertyAccessExpression */: - // A PAE alias is _always_ going to exist as an append to a top-level export, where our top level - // handling should always be sufficient to encode the export action itself - break; default: return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!"); } @@ -37903,7 +38014,8 @@ var ts; var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol); // serialize what the alias points to, preserve the declaration's initializer var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); - if (target) { + // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const + if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) { // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it // eg, `namespace A { export class B {} }; exports = A.B;` // Technically, this is all that's required in the case where the assignment is an entity name expression @@ -37978,6 +38090,7 @@ var ts; return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) && !getIndexInfoOfType(typeToSerialize, 0 /* String */) && !getIndexInfoOfType(typeToSerialize, 1 /* Number */) && + !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK !getDeclarationWithTypeAnnotation(hostSymbol) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && @@ -38121,7 +38234,7 @@ var ts; return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = getFirstIdentifier(node); + var leftmost = ts.getFirstIdentifier(node); var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); if (sym) { includePrivateSymbol(sym); @@ -38251,11 +38364,8 @@ var ts; return context.remappedSymbolNames.get("" + getSymbolId(symbol)); } } - if (input === "default" /* Default */) { - input = "_default"; - } - else if (input === "export=" /* ExportEquals */) { - input = "_exports"; + if (symbol) { + input = getNameCandidateWorker(symbol, input); } var i = 0; var original = input; @@ -38269,17 +38379,28 @@ var ts; } return input; } - function getInternalSymbolName(symbol, localName) { - if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) { - return context.remappedSymbolNames.get("" + getSymbolId(symbol)); - } + function getNameCandidateWorker(symbol, localName) { if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) { var flags = context.flags; context.flags |= 16777216 /* InInitialEntityName */; var nameCandidate = getNameOfSymbolAsWritten(symbol, context); context.flags = flags; - localName = ts.isIdentifierText(nameCandidate, languageVersion) && !ts.isStringANonContextualKeyword(nameCandidate) ? nameCandidate : getUnusedName("_default", symbol); + localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate; } + if (localName === "default" /* Default */) { + localName = "_default"; + } + else if (localName === "export=" /* ExportEquals */) { + localName = "_exports"; + } + localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_"); + return localName; + } + function getInternalSymbolName(symbol, localName) { + if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) { + return context.remappedSymbolNames.get("" + getSymbolId(symbol)); + } + localName = getNameCandidateWorker(symbol, localName); // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up context.remappedSymbolNames.set("" + getSymbolId(symbol), localName); return localName; @@ -38544,7 +38665,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); + var firstIdentifier = ts.getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); var id = importSymbol && "" + getSymbolId(importSymbol); if (importSymbol && !visited.has(id)) { @@ -38608,6 +38729,8 @@ var ts; return !!target.immediateBaseConstraint; case 6 /* JSDocTypeReference */: return !!getSymbolLinks(target).resolvedJSDocType; + case 7 /* ResolvedTypeArguments */: + return !!target.resolvedTypeArguments; } return ts.Debug.assertNever(propertyName); } @@ -38693,7 +38816,9 @@ var ts; } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); - return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + result.objectFlags |= 131072 /* ObjectRestType */; + return result; } // Determine the control flow type associated with a destructuring declaration or assignment. The following // forms of destructuring are possible: @@ -39079,23 +39204,23 @@ var ts; kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); - var members_3 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_3); + var members_4 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_3.has(name)) { + if (members_4.has(name)) { var exportedMember = exportedType_1.members.get(name); var union = createSymbol(s.flags | exportedMember.flags, name); union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_3.set(name, union); + members_4.set(name, union); } else { - members_3.set(name, s); + members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag return result; } @@ -39155,7 +39280,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -39295,16 +39420,12 @@ var ts; if (!declaration.statements.length) { return emptyObjectType; } - var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); - if (type_1.flags & 524288 /* Object */) { - return getRegularTypeOfObjectLiteral(type_1); - } - return type_1; + return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression))); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39372,7 +39493,7 @@ var ts; } if (!popTypeResolution()) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39455,7 +39576,9 @@ var ts; } else { ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -39501,11 +39624,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_2; + return type_1; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -39691,6 +39814,7 @@ var ts; // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 245 /* InterfaceDeclaration */); + ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -39721,7 +39845,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length === 1) { var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -40428,8 +40552,8 @@ var ts; var decl = _a[_i]; var members = ts.getMembersOfDeclaration(decl); if (members) { - for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { - var member = members_4[_b]; + for (var _b = 0, members_5 = members; _b < members_5.length; _b++) { + var member = members_5[_b]; if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { lateBindMember(symbol, earlySymbols, lateSymbols, member); } @@ -40558,8 +40682,8 @@ var ts; var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + var sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -40567,15 +40691,13 @@ var ts; sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; } function cloneSignature(sig) { var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -40587,13 +40709,25 @@ var ts; result.mapper = undefined; return result; } - function createOptionalCallSignature(signature) { + function getOptionalCallSignature(signature, callChainFlags) { + if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) { + return signature; + } + if (!signature.optionalCallSignatureCache) { + signature.optionalCallSignatureCache = {}; + } + var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer"; + return signature.optionalCallSignatureCache[key] + || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags)); + } + function createOptionalCallSignature(signature, callChainFlags) { + ts.Debug.assert(callChainFlags === 4 /* IsInnerCallChain */ || callChainFlags === 8 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both."); var result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= callChainFlags; return result; } function getExpandedParameters(sig) { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { var restIndex_1 = sig.parameters.length - 1; var restParameter = sig.parameters[restIndex_1]; var restType = getTypeOfSymbol(restParameter); @@ -40618,7 +40752,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJSFile(baseTypeNode); @@ -40782,11 +40916,9 @@ var ts; var params = combineUnionParameters(left, right); var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - var hasRestParam = left.hasRestParameter || right.hasRestParameter; - var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */); result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); return result; } @@ -40959,7 +41091,7 @@ var ts; var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray; if (symbol.flags & 16 /* Function */) { constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) : undefined; })); } if (!constructSignatures.length) { @@ -41465,8 +41597,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_3 = types_6[_i]; - var baseType = getBaseConstraint(type_3); + var type_2 = types_6[_i]; + var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } @@ -41899,7 +42031,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var flags = 0 /* None */; var minArgumentCount = 0; var thisParameter = void 0; var hasThisParameter = false; @@ -41930,7 +42062,7 @@ var ts; parameters.push(paramSymbol); } if (type && type.kind === 186 /* LiteralType */) { - hasLiteralTypes = true; + flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || @@ -41956,9 +42088,11 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1 /* HasRestParameter */; + } links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, - /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -42101,8 +42235,11 @@ var ts; signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, /*wasOptional*/ true); + if (signature.flags & 4 /* IsInnerCallChain */) { + type = addOptionalTypeMarker(type); + } + else if (signature.flags & 8 /* IsOuterCallChain */) { + type = getOptionalType(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -42158,7 +42295,7 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, 1 /* Number */); @@ -42375,7 +42512,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 1835008 /* PropagatingFlags */; + return result & 3670016 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -42409,13 +42546,25 @@ var ts; return type; } function getTypeArguments(type) { + var _a, _b; if (!type.resolvedTypeArguments) { + if (!pushTypeResolution(type, 7 /* ResolvedTypeArguments */)) { + return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray; + } var node = type.node; var typeArguments = !node ? ts.emptyArray : node.kind === 168 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : node.kind === 173 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode); - type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + if (popTypeResolution()) { + type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + } + else { + type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray; + error(type.node || currentNode, type.target.symbol + ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves + : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol)); + } } return type.resolvedTypeArguments; } @@ -42532,7 +42681,7 @@ var ts; errorType; } if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) { - var jsdocType = getTypeFromJSAlias(node, symbol); + var jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -42545,18 +42694,30 @@ var ts; return errorType; } /** - * A JSdoc TypeReference may be to a value imported from commonjs. - * These should really be aliases, but this special-case code fakes alias resolution - * by producing a type from a value. + * A JSdoc TypeReference may be to a value, but resolve it as a type anyway. + * Note: If the value is imported from commonjs, it should really be an alias, + * but this function's special-case code fakes alias resolution as well. */ - function getTypeFromJSAlias(node, symbol) { + function getTypeFromJSDocValueReference(node, symbol) { var valueType = getTypeOfSymbol(symbol); - var typeType = valueType.symbol && - valueType.symbol !== symbol && // Make sure this is a commonjs export by checking that symbol -> type -> symbol doesn't roundtrip. - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + var typeType = valueType; + if (symbol.valueDeclaration) { + var decl = ts.getRootDeclaration(symbol.valueDeclaration); + var isRequireAlias = false; + if (ts.isVariableDeclaration(decl) && decl.initializer) { + var expr = decl.initializer; + // skip past entity names, eg `require("x").a.b.c` + while (ts.isPropertyAccessExpression(expr)) { + expr = expr.expression; + } + isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol; + } + var isImportTypeWithQualifier = node.kind === 187 /* ImportType */ && node.qualifier; + if (isRequireAlias || isImportTypeWithQualifier) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable, substitute) { if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === typeVariable) { @@ -42985,7 +43146,7 @@ var ts; if (type === wildcardType) includes |= 4194304 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 262144 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) includes |= 2097152 /* IncludesNonWideningType */; } else { @@ -43112,7 +43273,7 @@ var ts; neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 131072 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -43262,7 +43423,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) & 131072 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -43271,7 +43432,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 131072 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -43300,7 +43461,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 131072 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -44097,7 +44258,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host)) { + while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 137 /* ReadonlyKeyword */) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -44198,7 +44359,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ @@ -44512,7 +44673,7 @@ var ts; // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */); result.target = signature; result.mapper = mapper; return result; @@ -45393,20 +45554,20 @@ var ts; } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, - /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */; } /** * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any` */ function isAnySignature(s) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } /** * See signatureRelatedTo, compareSignaturesIdentical */ - function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) { // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; @@ -45425,6 +45586,9 @@ var ts; var sourceCount = getParameterCount(source); var sourceRestType = getNonArrayRestType(source); var targetRestType = getNonArrayRestType(target); + if (sourceRestType || targetRestType) { + void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers); + } if (sourceRestType && targetRestType && sourceCount !== targetCount) { // We're not able to relate misaligned complex rest parameters return 0 /* False */; @@ -45468,7 +45632,7 @@ var ts; (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */); var related = callbacks ? // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is - compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) : + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { @@ -45482,13 +45646,13 @@ var ts; // If a signature resolution is already in-flight, skip issuing a circularity error // here and just use the `any` type directly var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType - : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(target.declaration.symbol) + : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol)) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType - : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(source.declaration.symbol) + : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol)) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); @@ -45675,7 +45839,7 @@ var ts; return true; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var related = relation.get(getRelationKey(source, target, relation)); + var related = relation.get(getRelationKey(source, target, /*isIntersectionConstituent*/ false, relation)); if (related !== undefined) { return !!(related & 1 /* Succeeded */); } @@ -46046,7 +46210,7 @@ var ts; // and we need to handle "each" relations before "some" relations for the same kind of type. if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), isIntersectionConstituent) : + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) : eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); } else { @@ -46084,7 +46248,7 @@ var ts; // // - For a primitive type or type parameter (such as 'number = A & B') there is no point in // breaking the intersection apart. - result = someTypeRelatedToType(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ true); + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { @@ -46197,7 +46361,7 @@ var ts; // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) - if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration)) { + if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) { // Note that extraneous children (as in `extra`) don't pass this check, // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute. errorNode = prop.valueDeclaration.name; @@ -46208,7 +46372,7 @@ var ts; // use the property's value declaration if the property is assigned inside the literal itself var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; - if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) { var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; @@ -46368,14 +46532,14 @@ var ts; } return result; } - function someTypeRelatedToType(source, target, reportErrors, isIntersectionConstituent) { + function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; for (var i = 0; i < len; i++) { - var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, isIntersectionConstituent); + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { return related; } @@ -46463,7 +46627,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, relation); + var id = getRelationKey(source, target, isIntersectionConstituent, relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -47357,7 +47521,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, incompatibleReporter, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, incompatibleReporter, isRelatedTo, reportUnreliableMarkers); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -47649,17 +47813,18 @@ var ts; * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. * For other cases, the types ids are used. */ - function getRelationKey(source, target, relation) { + function getRelationKey(source, target, isIntersectionConstituent, relation) { if (relation === identityRelation && source.id > target.id) { var temp = source; source = target; target = temp; } + var intersection = isIntersectionConstituent ? "&" : ""; if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { var typeParameters = []; - return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters); + return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + intersection; } - return source.id + "," + target.id; + return source.id + "," + target.id + intersection; } // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. @@ -47710,7 +47875,7 @@ var ts; // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`). function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 524288 /* Object */) { + if (depth >= 5 && type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { var symbol = type.symbol; if (symbol) { var count = 0; @@ -48085,37 +48250,19 @@ var ts; function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type) { + return type !== optionalType; + } function removeOptionalTypeMarker(type) { - return strictNullChecks ? filterType(type, function (t) { return t !== optionalType; }) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } - function propagateOptionalTypeMarker(type, wasOptional) { - return wasOptional ? addOptionalTypeMarker(type) : type; + function propagateOptionalTypeMarker(type, node, wasOptional) { + return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional, type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - function checkOptionalExpression(parent, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var isOptional = false; - var type = checkExpression(expression); - if (ts.isOptionalChain(parent)) { - if (parent.questionDotToken) { - // If we have a questionDotToken then we are an OptionalExpression and should remove `null` and - // `undefined` from the type and add the optionalType to the result, if needed. - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - // If we do not have a questionDotToken, then we are an OptionalChain and we remove the optionalType and - // indicate whether we need to add optionalType back into the result. - var nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType, expression) { + return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } /** * Is source potentially coercible to target type under `==`. @@ -48269,14 +48416,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 */ | 1048576 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* 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) & 786432 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -48321,7 +48468,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 262144 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -48347,7 +48494,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) & 262144 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -48427,7 +48574,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 262144 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -48544,7 +48691,7 @@ var ts; return !!(type.flags & 63176704 /* Instantiable */ || 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 */ || + objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { @@ -48599,7 +48746,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) & 1048576 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }); } function createReverseMappedType(source, target, constraint) { @@ -48750,10 +48897,7 @@ var ts; // inferring a type parameter constraint. Instead, make a lower priority inference from // the full source to whatever remains in the target. For example, when inferring from // string to 'string | T', make a lower priority inference of string for T. - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, 1 /* NakedTypeVariable */); return; } source = getUnionType(sources); @@ -48786,7 +48930,7 @@ 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) & 1048576 /* NonInferrableType */ || source === silentNeverType || (priority & 16 /* ReturnType */ && (source === autoType || source === autoArrayType))) { + if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === silentNeverType || (priority & 16 /* ReturnType */ && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -48853,10 +48997,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - var savePriority = priority; - priority |= 32 /* LiteralKeyof */; - inferFromTypes(empty, target.type); - priority = savePriority; + inferWithPriority(empty, target.type, 32 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -48908,6 +49049,12 @@ var ts; } } } + function inferWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -48973,6 +49120,18 @@ var ts; } return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types) { + var typeVariable; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var type = types_13[_i]; + var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } function inferToMultipleTypes(source, targets, targetFlags) { var typeVariableCount = 0; if (targetFlags & 1048576 /* Union */) { @@ -49002,6 +49161,16 @@ var ts; } } } + if (typeVariableCount === 0) { + // If every target is an intersection of types containing a single naked type variable, + // make a lower priority inference to that type variable. This handles inferring from + // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T. + var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */); + } + return; + } // If the target has a single naked type variable and no inference circularities were // encountered above (meaning we explored the types fully), create a union of the source // types from which no inferences have been made so far and infer from that union to the @@ -49033,15 +49202,12 @@ var ts; // we want to infer string for T, not Promise | string. For intersection types // we only infer to single naked type variables. if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) { - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) { var t = targets_4[_b]; if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, 1 /* NakedTypeVariable */); } } - priority = savePriority; } } function inferToMappedType(source, target, constraintType) { @@ -49062,14 +49228,12 @@ var ts; if (inference && !inference.isFixed) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - var savePriority = priority; // 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). - priority |= ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? - 4 /* PartialHomomorphicMappedType */ : 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? + 4 /* PartialHomomorphicMappedType */ : + 2 /* HomomorphicMappedType */); } } return true; @@ -49077,10 +49241,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. - var savePriority = priority; - priority |= 8 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, 8 /* 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 @@ -49189,7 +49350,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 1048576 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -49458,6 +49619,15 @@ var ts; } return false; } + function optionalChainContainsReference(source, target) { + while (ts.isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property // a possible discriminant if its type differs in the constituents of containing union type, and if every @@ -49578,8 +49748,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; result |= getTypeFacts(t); } return result; @@ -49948,8 +50118,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -50030,9 +50200,18 @@ var ts; // expressions are potential type predicate function calls. In order to avoid triggering // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. - var funcType = node.parent.kind === 225 /* ExpressionStatement */ ? getTypeOfDottedName(node.expression, /*diagnostic*/ undefined) : - node.expression.kind !== 101 /* SuperKeyword */ ? checkOptionalExpression(node, node.expression).type : - undefined; + var funcType = void 0; + if (node.parent.kind === 225 /* ExpressionStatement */) { + funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); + } + else if (node.expression.kind !== 101 /* SuperKeyword */) { + if (ts.isOptionalChain(node)) { + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */); var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -50045,6 +50224,13 @@ var ts; return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */); } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { + return callExpression.arguments[predicate.parameterIndex]; + } + var invokedExpression = ts.skipParentheses(callExpression.expression); + return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined; + } function reportFlowControlError(node) { var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); var sourceFile = ts.getSourceFileOfNode(node); @@ -50060,6 +50246,11 @@ var ts; function isUnlockedReachableFlowNode(flow) { return !(flow.flags & 4096 /* PreFinally */ && flow.lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); } + function isFalseExpression(expr) { + var node = ts.skipParentheses(expr); + return node.kind === 90 /* FalseKeyword */ || node.kind === 208 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); + } function isReachableFlowNodeWorker(flow, noCacheCheck) { while (true) { if (flow === lastFlowNode) { @@ -50079,8 +50270,17 @@ var ts; } else if (flags & 512 /* Call */) { var signature = getEffectsSignature(flow.node); - if (signature && getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { - return false; + if (signature) { + var predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3 /* AssertsIdentifier */) { + var predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { + return false; + } } flow = flow.antecedent; } @@ -50314,6 +50514,9 @@ var ts; } function narrowTypeByAssertion(type, expr) { var node = ts.skipParentheses(expr); + if (node.kind === 90 /* FalseKeyword */) { + return unreachableNeverType; + } if (node.kind === 208 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); @@ -50332,7 +50535,7 @@ var ts; var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : - predicate.kind === 3 /* AssertsIdentifier */ ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -50403,17 +50606,24 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } else if (expr.kind === 203 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); + } + else if (expr.kind === 203 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -50421,6 +50631,7 @@ var ts; var antecedentTypes = []; var subtypeReduction = false; var seenIncomplete = false; + var bypassFlow; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; if (antecedent.flags & 4096 /* PreFinally */ && antecedent.lock.locked) { @@ -50429,6 +50640,11 @@ var ts; // in this case we should ignore this branch. continue; } + if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) { + // The antecedent is the bypass branch of a potentially exhaustive switch statement. + bypassFlow = antecedent; + continue; + } var flowType = getTypeAtFlowNode(antecedent); var type = getTypeFromFlowType(flowType); // If the type at a particular antecedent path is the declared type and the @@ -50449,6 +50665,25 @@ var ts; seenIncomplete = true; } } + if (bypassFlow) { + var flowType = getTypeAtFlowNode(bypassFlow); + var type = getTypeFromFlowType(flowType); + // If the bypass flow contributes a type we haven't seen yet and the switch statement + // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase + // the risk of circularities, we only want to perform them when they make a difference. + if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) { + if (type === declaredType && declaredType === initialType) { + return type; + } + antecedentTypes.push(type); + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + } return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { @@ -50555,6 +50790,9 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } @@ -50603,6 +50841,14 @@ var ts; if (isMatchingReference(reference, right_1)) { return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + } + else if (optionalChainContainsReference(right_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left_1, declaredType)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } @@ -50626,6 +50872,15 @@ var ts; } return type; } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + // We are in a branch of obj?.foo === value or obj?.foo !== value. We remove undefined and null from + // the type of obj if (a) the operator is === and the type of value doesn't include undefined or (b) the + // operator is !== and the type of value is undefined. + var effectiveTrue = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */ ? assumeTrue : !assumeTrue; + var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */; + var valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? 262144 /* EQUndefinedOrNull */ : 65536 /* EQUndefined */)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* Any */) { return type; @@ -50673,8 +50928,14 @@ var ts; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands + if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, target)) { @@ -50682,9 +50943,6 @@ var ts; } return type; } - if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } @@ -50717,6 +50975,10 @@ var ts; return type; } } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { + var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify // values with unit types, except for the case where @@ -50849,6 +51111,9 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' // references might reference a different 'y' property. However, we make an exception @@ -50921,39 +51186,28 @@ var ts; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + var predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (ts.isAccessExpression(invokedExpression) && predicate.type) { - var possibleReference = ts.skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if (ts.isOptionalChainRoot(expr.parent) || + if (ts.isExpressionOfOptionalChainRoot(expr) || ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -51234,7 +51488,24 @@ var ts; } } else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { - error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + var diag = error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // See GH:32846 - if the user is using a variable whose type is () => T1 | ... | undefined + // they may have meant to specify the type as (() => T1 | ...) | undefined + // This is assumed if: the type is a FunctionType, the return type is a Union, the last constituent of + // the union is `undefined` + if (type.symbol && type.symbol.declarations.length === 1 && ts.isFunctionTypeNode(type.symbol.declarations[0])) { + var funcTypeNode = type.symbol.declarations[0]; + var returnType = getReturnTypeFromAnnotation(funcTypeNode); + if (returnType && returnType.flags & 1048576 /* Union */) { + var unionTypes_3 = funcTypeNode.type.types; + if (unionTypes_3 && unionTypes_3[unionTypes_3.length - 1].kind === 145 /* UndefinedKeyword */) { + var parenedFuncType = ts.getMutableClone(funcTypeNode); + // Highlight to the end of the second to last constituent of the union + parenedFuncType.end = unionTypes_3[unionTypes_3.length - 2].end; + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(parenedFuncType, ts.Diagnostics.Did_you_mean_to_parenthesize_this_function_type)); + } + } + } // Return the declared type to reduce follow-on errors return type; } @@ -52014,18 +52285,22 @@ var ts; return undefined; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget, arg) { + function getContextualTypeForArgument(callTarget, arg, contextFlags) { var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + function getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & 4 /* Completion */ && signature.target) { + var baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { @@ -52384,7 +52659,7 @@ var ts; } /* falls through */ case 196 /* NewExpression */: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case 198 /* TypeAssertionExpression */: case 216 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); @@ -52599,8 +52874,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -52701,7 +52976,7 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 524288 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; } return literalType; } @@ -52838,7 +53113,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 1835008 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -52947,7 +53222,7 @@ 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 */ | 524288 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { result.objectFlags |= 16384 /* JSLiteral */; } @@ -53045,7 +53320,7 @@ var ts; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 1835008 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -53125,7 +53400,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 */ | 524288 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -53597,8 +53872,8 @@ var ts; function symbolHasNonMethodDeclaration(symbol) { return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } - function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */); @@ -53606,22 +53881,34 @@ var ts; function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + function reportObjectPossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + } + function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? - (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + reportError(node, kind); var t = getNonNullableType(type); return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) { @@ -53630,10 +53917,16 @@ var ts; return nonNullType; } function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + function checkPropertyAccessChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); } function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node) { while (node.parent.kind === 199 /* ParenthesizedExpression */) { @@ -53641,8 +53934,7 @@ var ts; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var _a = checkOptionalExpression(node, left), isOptional = _a.isOptional, leftType = _a.type; + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -53695,7 +53987,7 @@ var ts; } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { // Only compute control flow type if this is a property access expression that isn't an @@ -54017,7 +54309,15 @@ var ts; return false; } function checkIndexedAccess(node) { - var _a = checkOptionalExpression(node, node.expression), isOptional = _a.isOptional, exprType = _a.type; + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + function checkElementAccessChain(node) { + var exprType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -54033,7 +54333,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -54104,7 +54404,7 @@ var ts; // interface B extends A { (x: 'foo'): string } // const b: B; // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] - function reorderCandidates(signatures, result, isOptionalCall) { + function reorderCandidates(signatures, result, callChainFlags) { var lastParent; var lastSymbol; var cutoffIndex = 0; @@ -54134,7 +54434,7 @@ var ts; lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -54145,7 +54445,7 @@ var ts; else { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature); } } function isSpreadArgument(arg) { @@ -54229,7 +54529,7 @@ var ts; // the declared number of type parameters, the call has an incorrect arity. var numTypeParameters = ts.length(signature.typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - return !typeArguments || + return !ts.some(typeArguments) || (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. @@ -54440,7 +54740,19 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var thisArgumentType = void 0; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (ts.isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -54667,7 +54979,7 @@ var ts; 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.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_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 (min < argCount && argCount < max) { @@ -54723,7 +55035,7 @@ var ts; } return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } - function resolveCall(node, signatures, candidatesOutArray, checkMode, isOptionalCall, fallbackError) { + function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { var isTaggedTemplate = node.kind === 197 /* TaggedTemplateExpression */; var isDecorator = node.kind === 156 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -54738,7 +55050,7 @@ var ts; } var candidates = candidatesOutArray || []; // reorderCandidates fills up the candidates array directly - reorderCandidates(signatures, candidates, isOptionalCall); + reorderCandidates(signatures, candidates, callChainFlags); if (!candidates.length) { if (reportErrors) { diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); @@ -54900,7 +55212,7 @@ var ts; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) { @@ -54918,7 +55230,7 @@ var ts; var inferenceContext = void 0; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - if (typeArguments) { + if (ts.some(typeArguments)) { typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); if (!typeArgumentTypes) { candidateForTypeArgumentError = candidate; @@ -54993,34 +55305,34 @@ var ts; var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; var _loop_15 = function (i) { - var symbols = ts.mapDefined(candidates, function (_a) { - var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; - return hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : - i < parameters.length ? parameters[i] : undefined; - }); + var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined; }); ts.Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { _loop_15(i); } - var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); - var hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); + var flags = 0 /* None */; + if (restParameterSymbols.length !== 0) { var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1 /* HasRestParameter */; + } + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2 /* HasLiteralTypes */; } return createSignature(candidates[0].declaration, /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. thisParameter, parameters, /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), - /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, - /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + /*typePredicate*/ undefined, minArgumentCount, flags); } function getNumNonRestParameters(signature) { var numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); @@ -55096,12 +55408,24 @@ var ts; var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */); } } return resolveUntypedCall(node); } - var _b = checkOptionalExpression(node, node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined), isOptional = _b.isOptional, funcType = _b.type; + var callChainFlags; + var funcType = checkExpression(node.expression); + if (ts.isCallChain(node)) { + var nonOptionalType = getOptionalExpressionType(funcType, node.expression); + callChainFlags = nonOptionalType === funcType ? 0 /* None */ : + ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ : + 4 /* IsInnerCallChain */; + funcType = nonOptionalType; + } + else { + callChainFlags = 0 /* None */; + } + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -55167,7 +55491,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, isOptional); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags); } function isGenericFunctionReturningFunction(signature) { return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature))); @@ -55230,7 +55554,7 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */); } // If expressionType's apparent type is an object type with no construct signatures but // one or more call signatures, the expression is processed as a function call. A compile-time @@ -55238,7 +55562,7 @@ var ts; // operation is Any. It is an error to have a Void this type. var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); if (!noImplicitAny) { if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); @@ -55323,8 +55647,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var constituent = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var constituent = types_17[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -55415,7 +55739,7 @@ var ts; invocationError(node.tag, apparentType, 0 /* Call */); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); } /** * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. @@ -55468,7 +55792,7 @@ var ts; invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, checkMode, /*isOptional*/ false, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage); } function createSignatureForJSXIntrinsic(node, result) { var namespace = getJsxNamespaceAt(node); @@ -55483,9 +55807,7 @@ var ts; return createSignature(declaration, /*typeParameters*/ undefined, /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, - /*returnTypePredicate*/ undefined, 1, - /*hasRestparameter*/ false, - /*hasLiteralTypes*/ false); + /*returnTypePredicate*/ undefined, 1, 0 /* None */); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -55508,7 +55830,7 @@ var ts; error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); return resolveErrorCall(node); } - return resolveCall(node, signatures, candidatesOutArray, checkMode, /*isOptional*/ false); + return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */); } /** * Sometimes, we have a decorator that could accept zero arguments, @@ -55518,7 +55840,7 @@ var ts; function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } @@ -55589,7 +55911,7 @@ var ts; return false; } function mergeJSSymbols(target, source) { - if (source && (ts.hasEntries(source.exports) || ts.hasEntries(source.members))) { + if (source) { var links = getSymbolLinks(source); if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) { var inferred = isTransientSymbol(target) ? target : cloneSymbol(target); @@ -55899,7 +56221,7 @@ var ts; return type; } function getParameterNameAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -55916,11 +56238,11 @@ var ts; return tryGetTypeAtPosition(signature, pos) || anyType; } function tryGetTypeAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // We want to return the value undefined for an out of bounds parameter position, // so we need to check bounds here before calling getIndexedAccessType (which // otherwise would return the type 'undefined'). @@ -55955,7 +56277,7 @@ var ts; } function getParameterCount(signature) { var length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -55964,7 +56286,7 @@ var ts; return length; } function getMinArgumentCount(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { var minLength = restType.target.minLength; @@ -55976,14 +56298,14 @@ var ts; return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } return false; } function getEffectiveRestType(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -56000,7 +56322,7 @@ var ts; return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, inferenceContext) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -56033,7 +56355,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } } - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56041,7 +56363,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56318,8 +56640,8 @@ var ts; var witnesses = getSwitchClauseTypeOfWitnesses(node); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_4 = getBaseConstraintOfType(operandType) || operandType; - return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + var type_3 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -56446,9 +56768,9 @@ var ts; return links.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + 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 |= 1048576 /* NonInferrableType */; + returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } return anyFunctionType; @@ -56677,8 +56999,7 @@ var ts; var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); var func = ts.getContainingFunction(node); - if (func && func.kind !== 161 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + if (func && func.kind !== 161 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -56779,8 +57100,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -57414,25 +57735,10 @@ var ts; } return [effectiveLeft, effectiveRight]; } - function isYieldExpressionInClass(node) { - var current = node; - var parent = node.parent; - while (parent) { - if (ts.isFunctionLike(parent) && current === parent.body) { - return false; - } - else if (ts.isClassLike(current)) { - return true; - } - current = parent; - parent = parent.parent; - } - return false; - } function checkYieldExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 8192 /* YieldContext */) || isYieldExpressionInClass(node)) { + if (!(node.flags & 8192 /* YieldContext */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -57768,6 +58074,18 @@ var ts; } } } + function getReturnTypeOfSingleNonGenericCallSignature(funcType) { + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) { + var funcType = checkExpression(expr.expression); + var nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType); + return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType); + } /** * Returns the type of an expression. Unlike checkExpression, this function is simply concerned * with computing the type and may not fully check all contained sub-expressions for errors. @@ -57779,10 +58097,10 @@ var ts; // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. if (ts.isCallExpression(expr) && expr.expression.kind !== 101 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { - var _a = checkOptionalExpression(expr, expr.expression), isOptional = _a.isOptional, funcType = _a.type; - var signature = getSingleCallSignature(funcType); - if (signature && !signature.typeParameters) { - return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); + var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : + getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression)); + if (type) { + return type; } } else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) { @@ -57832,7 +58150,7 @@ var ts; (node.parent.kind === 194 /* ElementAccessExpression */ && node.parent.expression === node) || ((node.kind === 75 /* Identifier */ || node.kind === 152 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || (node.parent.kind === 171 /* TypeQuery */ && node.parent.exprName === node)) || - (node.parent.kind === 261 /* ExportSpecifier */ && (compilerOptions.preserveConstEnums || node.flags & 8388608 /* Ambient */)); // We allow reexporting const enums + (node.parent.kind === 261 /* ExportSpecifier */); // We allow reexporting const enums if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -58036,7 +58354,7 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -59211,7 +59529,7 @@ var ts; return; } // Verify there is no local declaration that could collide with the promise constructor. - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); @@ -59268,7 +59586,7 @@ var ts; function markEntityNameOrEntityExpressionAsReference(typeName) { if (!typeName) return; - var rootName = getFirstIdentifier(typeName); + var rootName = ts.getFirstIdentifier(typeName); var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol @@ -59308,8 +59626,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var typeNode = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var typeNode = types_19[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -61084,10 +61402,7 @@ var ts; firstDefaultClause = clause; } else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -61108,6 +61423,9 @@ var ts; } } ts.forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -61630,11 +61948,13 @@ var ts; // same when the derived property is from an assignment continue; } - if (basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property; - } - else if (basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor; + var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */; + var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */; + if (overriddenInstanceProperty || overriddenInstanceAccessor) { + var errorMessage_1 = overriddenInstanceProperty ? + ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : + 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 { var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 158 /* PropertyDeclaration */ && !d.initializer; }); @@ -61650,24 +61970,22 @@ var ts; || !ts.isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { - var errorMessage_1 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; - error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType)); + var errorMessage_2 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType)); } } - // correct case - continue; } + // correct case + continue; } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { - // method is overridden with method -- correct case + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { + // method is overridden with method or property -- correct case continue; } - else if (derived.flags & 98304 /* Accessor */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & 98304 /* Accessor */) { @@ -62173,22 +62491,6 @@ var ts; break; } } - function getFirstIdentifier(node) { - switch (node.kind) { - case 75 /* Identifier */: - return node; - case 152 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 75 /* Identifier */); - return node; - case 193 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 75 /* Identifier */); - return node; - } - } function getFirstNonModuleExportsIdentifier(node) { switch (node.kind) { case 75 /* Identifier */: @@ -62318,7 +62620,7 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - var moduleName = getFirstIdentifier(node.moduleReference); + var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } @@ -62385,7 +62687,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -64691,10 +64993,10 @@ var ts; if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -65577,7 +65879,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -65647,6 +65949,14 @@ var ts; case 2 /* Next */: return "nextType"; } } + function signatureHasRestParameter(s) { + return !!(s.flags & 1 /* HasRestParameter */); + } + ts.signatureHasRestParameter = signatureHasRestParameter; + function signatureHasLiteralTypes(s) { + return !!(s.flags & 2 /* HasLiteralTypes */); + } + ts.signatureHasLiteralTypes = signatureHasLiteralTypes; })(ts || (ts = {})); var ts; (function (ts) { @@ -66580,7 +66890,9 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } // Because we are updating existed propertyAccess we want to inherit its emitFlags // instead of using the default from createPropertyAccess return node.expression !== expression @@ -66618,7 +66930,9 @@ var ts; } ts.createElementAccess = createElementAccess; function updateElementAccess(node, expression, argumentExpression) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -66652,7 +66966,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (ts.isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -67254,7 +67570,7 @@ var ts; var node = createSynthesizedNode(231 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -69780,7 +70096,7 @@ var ts; var conditionalPrecedence = ts.getOperatorPrecedence(209 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { return ts.createParen(condition); } return condition; @@ -70378,6 +70694,12 @@ var ts; * Gets the property name of a BindingOrAssignmentElement */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement); + ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element."); + return propertyName; + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { case 190 /* BindingElement */: // `a` in `let { a: b } = ...` @@ -70413,9 +70735,8 @@ var ts; ? target.expression : target; } - ts.Debug.fail("Invalid property name for binding element."); } - ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; function isStringOrNumericLiteral(node) { var kind = node.kind; return kind === 10 /* StringLiteral */ @@ -72434,7 +72755,8 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node)) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); @@ -72503,6 +72825,17 @@ var ts; } return false; } + function bindingOrAssignmentElementContainsNonLiteralComputedName(element) { + var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element); + if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) { + return true; + } + var target = ts.getTargetOfBindingOrAssignmentElement(element); + return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target); + } + function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) { + return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName); + } /** * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * @@ -72533,7 +72866,8 @@ var ts; }; if (ts.isVariableDeclaration(node)) { var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); - if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node))) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); @@ -73832,8 +74166,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { - var member = members_5[_i]; + for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { + var member = members_6[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -74223,8 +74557,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -74836,7 +75170,12 @@ var ts; * * @param node The module declaration node. */ - function shouldEmitModuleDeclaration(node) { + function shouldEmitModuleDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration); + if (!node) { + // If we can't find a parse tree node, assume the node is instantiated. + return true; + } return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } /** @@ -75655,7 +75994,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); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -77412,7 +77751,7 @@ var ts; } return ts.updateParen(node, expression); } - function visitNonOptionalPropertyAccessExpression(node, captureThisArg) { + function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg) { if (ts.isOptionalChain(node)) { // If `node` is an optional chain, then it is the outermost chain of an optional expression. return visitOptionalExpression(node, captureThisArg); @@ -77421,27 +77760,17 @@ var ts; ts.Debug.assertNotNode(expression, ts.isSyntheticReference); var thisArg; if (captureThisArg) { - // `a.b` -> { expression: `(_a = a).b`, thisArg: `_a` } - thisArg = ts.createTempVariable(hoistVariableDeclaration); - expression = ts.createParen(ts.createAssignment(thisArg, expression)); + if (shouldCaptureInTempVariable(expression)) { + thisArg = ts.createTempVariable(hoistVariableDeclaration); + expression = ts.createAssignment(thisArg, expression); + } + else { + thisArg = expression; + } } - expression = ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)); - return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression; - } - function visitNonOptionalElementAccessExpression(node, captureThisArg) { - if (ts.isOptionalChain(node)) { - // If `node` is an optional chain, then it is the outermost chain of an optional expression. - return visitOptionalExpression(node, captureThisArg); - } - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - ts.Debug.assertNotNode(expression, ts.isSyntheticReference); - var thisArg; - if (captureThisArg) { - // `a[b]` -> { expression: `(_a = a)[b]`, thisArg: `_a` } - thisArg = ts.createTempVariable(hoistVariableDeclaration); - expression = ts.createParen(ts.createAssignment(thisArg, expression)); - } - expression = ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); + expression = node.kind === 193 /* PropertyAccessExpression */ + ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) + : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression; } function visitNonOptionalCallExpression(node, captureThisArg) { @@ -77454,8 +77783,8 @@ var ts; function visitNonOptionalExpression(node, captureThisArg) { switch (node.kind) { case 199 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg); - case 193 /* PropertyAccessExpression */: return visitNonOptionalPropertyAccessExpression(node, captureThisArg); - case 194 /* ElementAccessExpression */: return visitNonOptionalElementAccessExpression(node, captureThisArg); + case 193 /* PropertyAccessExpression */: + case 194 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg); case 195 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } @@ -77463,31 +77792,36 @@ var ts; function visitOptionalExpression(node, captureThisArg) { var _a = flattenChain(node), expression = _a.expression, chain = _a.chain; var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0])); - var temp = ts.createTempVariable(hoistVariableDeclaration); var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined; var leftExpression = ts.isSyntheticReference(left) ? left.expression : left; - var rightExpression = temp; + var capturedLeft = leftExpression; + if (shouldCaptureInTempVariable(leftExpression)) { + capturedLeft = ts.createTempVariable(hoistVariableDeclaration); + leftExpression = ts.createAssignment(capturedLeft, leftExpression); + } + var rightExpression = capturedLeft; var thisArg; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { case 193 /* PropertyAccessExpression */: - if (i === chain.length - 1 && captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - rightExpression = ts.createParen(ts.createAssignment(thisArg, rightExpression)); - } - rightExpression = ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)); - break; case 194 /* ElementAccessExpression */: if (i === chain.length - 1 && captureThisArg) { - thisArg = ts.createTempVariable(hoistVariableDeclaration); - rightExpression = ts.createParen(ts.createAssignment(thisArg, rightExpression)); + if (shouldCaptureInTempVariable(rightExpression)) { + thisArg = ts.createTempVariable(hoistVariableDeclaration); + rightExpression = ts.createAssignment(thisArg, rightExpression); + } + else { + thisArg = rightExpression; + } } - rightExpression = ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); + rightExpression = segment.kind === 193 /* PropertyAccessExpression */ + ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) + : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; case 195 /* CallExpression */: if (i === 0 && leftThisArg) { - rightExpression = ts.createFunctionCall(rightExpression, leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); + rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 101 /* SuperKeyword */ ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } else { rightExpression = ts.createCall(rightExpression, @@ -77497,22 +77831,27 @@ var ts; } ts.setOriginalNode(rightExpression, segment); } - var target = ts.createConditional(ts.createLogicalOr(ts.createStrictEquality(ts.createAssignment(temp, leftExpression), ts.createNull()), ts.createStrictEquality(temp, ts.createVoidZero())), ts.createVoidZero(), rightExpression); + var target = ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createVoidZero(), rightExpression); return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target; } - function createNotNullCondition(node) { - return ts.createBinary(ts.createBinary(node, ts.createToken(37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(55 /* AmpersandAmpersandToken */), ts.createBinary(node, ts.createToken(37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero())); + function createNotNullCondition(left, right, invert) { + return ts.createBinary(ts.createBinary(left, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(invert ? 56 /* BarBarToken */ : 55 /* AmpersandAmpersandToken */), ts.createBinary(right, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero())); } function transformNullishCoalescingExpression(node) { - var expressions = []; var left = ts.visitNode(node.left, visitor, ts.isExpression); - if (!ts.isIdentifier(left)) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - expressions.push(ts.createAssignment(temp, left)); - left = temp; + var right = left; + if (shouldCaptureInTempVariable(left)) { + right = ts.createTempVariable(hoistVariableDeclaration); + left = ts.createAssignment(right, left); } - expressions.push(ts.createParen(ts.createConditional(createNotNullCondition(left), left, ts.visitNode(node.right, visitor, ts.isExpression)))); - return ts.inlineExpressions(expressions); + return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression)); + } + function shouldCaptureInTempVariable(expression) { + // don't capture identifiers and `this` in a temporary variable + // `super` cannot be captured as it's no real variable + return !ts.isIdentifier(expression) && + expression.kind !== 103 /* ThisKeyword */ && + expression.kind !== 101 /* SuperKeyword */; } } ts.transformESNext = transformESNext; @@ -87670,6 +88009,7 @@ var ts; var combinedStatements; if (ts.isSourceFileJS(currentSourceFile)) { combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); } else { @@ -89441,7 +89781,11 @@ var ts; bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) + return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) + emitSkipped = true; return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -92195,8 +92539,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_20 = types; _d < types_20.length; _d++) { - var directive = types_20[_d]; + for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { + var directive = types_21[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -94071,31 +94415,39 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (system.directoryExists(directoryPath)) { + if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } return false; } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - if (compilerHost.createDirectory) { - compilerHost.createDirectory(directoryPath); - } - else { - system.createDirectory(directoryPath); + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + // NOTE: If patchWriteFileEnsuringDirectory has been called, + // the system.writeFile will do its own directory creation and + // the ensureDirectoriesExist call will always be redundant. + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); } } } var outputFingerprints; - function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + function writeFileWorker(fileName, data, writeByteOrderMark) { + if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) { + system.writeFile(fileName, data, writeByteOrderMark); + return; + } if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = system.createHash(data); // TODO: GH#18217 - var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); + var mtimeBefore = system.getModifiedTime(fileName); if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -94107,32 +94459,13 @@ var ts; } } system.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, mtime: mtimeAfter }); } - function writeFile(fileName, data, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { - writeFileIfUpdated(fileName, data, writeByteOrderMark); - } - else { - system.writeFile(fileName, data, writeByteOrderMark); - } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -95854,9 +96187,16 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - if (fail) - fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + var canonicalFileName_1 = host.getCanonicalFileName(fileName); + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) { + if (fail) { + if (ts.hasJSFileExtension(canonicalFileName_1)) { + fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName); + } + else { + fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + } + } return undefined; } var sourceFile = getSourceFile(fileName); @@ -95870,7 +96210,7 @@ var ts; fail(ts.Diagnostics.File_0_not_found, fileName); } } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) { fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); } } @@ -95928,6 +96268,19 @@ var ts; function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) { if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(fileName); + // If preserveSymlinks is true, module resolution wont jump the symlink + // but the resolved real path may be the .d.ts from project reference + // Note:: Currently we try the real path only if the + // file is from node_modules to avoid having to run real path on all file paths + if (!source && + host.realpath && + options.preserveSymlinks && + ts.isDeclarationFileName(fileName) && + ts.stringContains(fileName, ts.nodeModulesPathPart)) { + var realPath = host.realpath(fileName); + if (realPath !== fileName) + source = getSourceOfProjectReferenceRedirect(realPath); + } if (source) { var file_1 = ts.isString(source) ? findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) : @@ -96458,9 +96811,6 @@ var ts; else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && ts.isIncrementalCompilation(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { @@ -97505,6 +97855,7 @@ var ts; ts.Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = ts.createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -98235,7 +98586,7 @@ var ts; } var state = { fileInfos: fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), @@ -98271,33 +98622,6 @@ var ts; } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; - function convertFromReusableCompilerOptions(options, toAbsolutePath) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - function convertFromReusableCompilerOptionValue(option, value, toAbsolutePath) { - if (option) { - if (option.type === "list") { - var values = value; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value); - } - } - return value; - } function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -99030,7 +99354,7 @@ var ts; function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { return { relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, - ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? + ending: ts.hasJSFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, }; @@ -99116,7 +99440,7 @@ var ts; var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } function numberOfDirectorySeparators(str) { @@ -99250,10 +99574,13 @@ var ts; // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); + var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { return undefined; + } // If the module was found in @types, get the actual Node package name var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); @@ -99478,7 +99805,7 @@ var ts; /** Parses config file using System interface */ function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; @@ -99502,7 +99829,7 @@ var ts; } ts.getErrorSummaryText = getErrorSummaryText; function listFiles(program, writeFileName) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { ts.forEach(program.getSourceFiles(), function (file) { writeFileName(file.fileName); }); @@ -99513,6 +99840,7 @@ var ts; * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -99521,13 +99849,17 @@ var ts; // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + if (!isListFilesOnly) { + ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + } } } // Emit and report any errors we ran into. - var emitResult = program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + var emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: ts.emptyArray } + : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics; ts.addRange(diagnostics, emitDiagnostics); ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); @@ -99630,19 +99962,13 @@ var ts; createHash: ts.maybeBind(host, host.createHash), readDirectory: ts.maybeBind(host, host.readDirectory), }; - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - if (host.createDirectory) - host.createDirectory(directoryPath); - } - } function writeFile(fileName, text, writeByteOrderMark, onError) { try { ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); + // NOTE: If patchWriteFileEnsuringDirectory has been called, + // the host.writeFile will do its own directory creation and + // the ensureDirectoriesExist call will always be redundant. + ts.writeFileEnsuringDirectories(fileName, text, writeByteOrderMark, function (path, data, writeByteOrderMark) { return host.writeFile(path, data, writeByteOrderMark); }, function (path) { return host.createDirectory(path); }, function (path) { return host.directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -101419,30 +101745,25 @@ var ts; setupInitialBuild(state, cancellationToken); var reportQueue = true; var successfulProjects = 0; - var errorProjects = 0; while (true) { var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; - } } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ts.ExitStatus.DiagnosticsPresent_OutputsGenerated : - ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : - ts.ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); }) + ? ts.ExitStatus.Success + : successfulProjects + ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated + : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); @@ -101450,7 +101771,7 @@ var ts; return ts.ExitStatus.InvalidProject_OutputsSkipped; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped; } var options = state.options, host = state.host; var filesToDelete = options.dry ? [] : undefined; diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index 2eb27cd9054..062df5844c9 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -441,7 +441,7 @@ "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "函数实现缺失或未立即出现在声明之后。", "Function_implementation_name_must_be_0_2389": "函数实现名称必须为“{0}”。", "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "由于函数不具有返回类型批注并且在它的一个返回表达式中得到直接或间接引用,因此它隐式具有返回类型 \"any\"。", - "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函数缺少结束返回语句,返回类型不包括 \"undefined\"。", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函数缺少结束 return 语句,返回类型不包括 \"undefined\"。", "Function_overload_must_be_static_2387": "函数重载必须为静态。", "Function_overload_must_not_be_static_2388": "函数重载不能为静态。", "Generate_get_and_set_accessors_95046": "生成 \"get\" 和 \"set\" 访问器", @@ -536,7 +536,7 @@ "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 元素不能具有多个名称相同的特性。", "JSX_expressions_must_have_one_parent_element_2657": "JSX 表达式必须具有一个父元素。", "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX 片段没有相应的结束标记。", - "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "使用内联 JSX 工厂杂注时,不支持 JSX 片段", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "使用内联 JSX 工厂 pragma 时,不支持 JSX 片段", "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "使用 --jsxFactory 时不支持 JSX 片段", "JSX_spread_child_must_be_an_array_type_2609": "JSX 扩展子属性必须为数组类型。", "Jump_target_cannot_cross_function_boundary_1107": "跳转目标不能跨越函数边界。",