diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json index 54e1c7ceccb..ec08f5e3112 100644 --- a/lib/cs/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Všechny deklarace {0} musí mít stejné modifikátory.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Všechny deklarace {0} musí mít stejné parametry typu.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Všechny deklarace abstraktní metody musí jít po sobě.", + "All_destructured_elements_are_unused_6198": "Žádný z destrukturovaných elementů se nepoužívá.", "All_imports_in_import_declaration_are_unused_6192": "Žádné importy z deklarace importu se nepoužívají.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Povolte výchozí importy z modulů bez výchozího exportu. Nebude to mít vliv na generování kódu, jenom na kontrolu typů.", "Allow_javascript_files_to_be_compiled_6102": "Povolí kompilaci souborů javascript.", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Nejde vyvolat objekt, který může být null.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Nejde vyvolat objekt, který může být null nebo nedefinovaný.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Nejde vyvolat objekt, který může být nedefinovaný.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Projekt {0} se nedá předřadit, protože nemá nastavenou hodnotu outFile.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Typ nejde znovu exportovat, pokud je zadaný příznak --isolatedModules.", "Cannot_read_file_0_Colon_1_5012": "Nejde číst soubor {0}: {1}", "Cannot_redeclare_block_scoped_variable_0_2451": "Nejde předeklarovat proměnnou bloku {0}.", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Zkompilujte projekt podle cesty k jeho konfiguračnímu souboru nebo do složky se souborem tsconfig.json.", "Compiler_option_0_expects_an_argument_6044": "Parametr kompilátoru {0} očekává argument.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Parametr kompilátoru {0} vyžaduje hodnotu typu {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Složené projekty nemůžou zakázat generování deklarací.", "Computed_property_names_are_not_allowed_in_enums_1164": "Názvy počítaných vlastností se ve výčtech nepovolují.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Ve výčtu, jehož členy mají hodnoty typu string, se nepovolují vypočítané hodnoty.", "Concatenate_and_emit_output_to_single_file_6001": "Zřetězit a generovat výstup do jednoho souboru", @@ -328,8 +331,8 @@ "Duplicate_label_0_1114": "Duplicitní popisek {0}", "Duplicate_number_index_signature_2375": "Duplicitní podpis číselného indexu", "Duplicate_string_index_signature_2374": "Duplicitní signatury řetězcového indexu", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Když se cílí na moduly ECMAScript 2015, nejde dynamický import použít.", "Dynamic_import_cannot_have_type_arguments_1326": "Dynamický import nemůže mít argumenty typu.", + "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_import_must_have_one_specifier_as_an_argument_1324": "Dynamický import musí mít jako argument jeden specifikátor.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specifikátor dynamického importu musí být typu string, ale tady má typ {0}.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Element má implicitně typ any, protože indexový výraz není typu number.", @@ -338,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Vygeneruje jediný soubor se zdrojovými mapováními namísto samostatného souboru.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Vygeneruje zdroj spolu se zdrojovými mapováními v jednom souboru. Vyžaduje, aby byla nastavená možnost --inlineSourceMap nebo --sourceMap.", "Enable_all_strict_type_checking_options_6180": "Povolí všechny možnosti striktní kontroly typů.", + "Enable_project_compilation_6302": "Povolit kompilování projektu", "Enable_strict_checking_of_function_types_6186": "Povolí striktní kontrolu typů funkcí.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Povolí striktní kontrolu inicializace vlastností ve třídách.", "Enable_strict_null_checks_6113": "Povolte striktní kontroly hodnot null.", @@ -399,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Soubor {0} má nepodporovanou příponu, a proto se přeskočí.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Soubor {0} má nepodporovanou příponu. Jediné podporované přípony jsou {1}.", "File_0_is_not_a_module_2306": "Soubor {0} není modul.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Soubor {0} se nenachází v seznamu souborů projektu. Projekty musí uvádět všechny soubory nebo používat vzor include.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Soubor {0} není pod kořenovým adresářem rootDir {1}. Očekává se, že rootDir bude obsahovat všechny zdrojové soubory.", "File_0_not_found_6053": "Soubor {0} se nenašel.", "File_change_detected_Starting_incremental_compilation_6032": "Zjistila se změna souboru. Spouští se přírůstková kompilace...", @@ -463,7 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Inicializátor členu v deklaracích ambientního výčtu musí být konstantní výraz.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Ve výčtu s víc deklaracemi může být jenom u jedné deklarace vynechaný inicializátor u prvního elementu výčtu.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "V inicializátoru člena deklarací výčtu const musí být konstantní výraz.", - "Include_modules_imported_with_json_extension_6197": "Include modules imported with '.json' extension", + "Include_modules_imported_with_json_extension_6197": "Zahrnout moduly importované s příponou .json", "Index_signature_in_type_0_only_permits_reading_2542": "Signatura indexu v typu {0} povoluje jen čtení.", "Index_signature_is_missing_in_type_0_2329": "V typu {0} chybí signatura indexu.", "Index_signatures_are_incompatible_2330": "Signatury indexu jsou nekompatibilní.", @@ -562,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Název modulu {0} byl úspěšně přeložen na {1}. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Druh překladu modulu nebyl určen, použije se {0}.", "Module_resolution_using_rootDirs_has_failed_6111": "Překlad modulu pomocí rootDirs se nepovedl.", + "Move_to_a_new_file_95049": "Move to a new file", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Více po sobě jdoucích číselných oddělovačů se nepovoluje.", "Multiple_constructor_implementations_are_not_allowed_2392": "Víc implementací konstruktoru se nepovoluje.", "NEWLINE_6061": "NOVÝ ŘÁDEK", @@ -603,9 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Možnost isolatedModules jde použít jenom v případě, že je poskytnutá možnost --module nebo že možnost target je ES2015 nebo vyšší verze.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Možnost paths se nedá použít bez zadání možnosti --baseUrl.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Možnost project se na příkazovém řádku nedá kombinovat se zdrojovým souborem.", - "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Možnost --resolveJsonModule se nedá zadat bez strategie překladu modulu node.", "Options_Colon_6027": "Možnosti:", "Output_directory_for_generated_declaration_files_6166": "Výstupní adresář pro vygenerované soubory deklarace", + "Output_file_0_from_project_1_does_not_exist_6309": "Výstupní soubor {0} z projektu {1} neexistuje.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Výstupní soubor {0} se nesestavil ze zdrojového souboru {1}.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "Signatura přetížení není kompatibilní s implementací funkce.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Signatury přetížení musí být všechny abstraktní nebo neabstraktní.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Signatury přetížení musí být všechny ambientní nebo neambientní.", @@ -649,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Část kompilace, při které se vypisují názvy generovaných souborů", "Print_the_compiler_s_version_6019": "Vytisknout verzi kompilátoru", "Print_this_message_6017": "Vytisknout tuto zprávu", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odkazy projektu nemůžou tvořit cyklický graf. Zjistil se cyklus: {0}", + "Projects_to_reference_6300": "Projekty, které se mají odkazovat", "Property_0_does_not_exist_on_const_enum_1_2479": "Vlastnost {0} ve výčtu const {1} neexistuje.", "Property_0_does_not_exist_on_type_1_2339": "Vlastnost {0} v typu {1} neexistuje.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Vlastnost {0} v typu {1} neexistuje. Nezapomněli jste použít await?", @@ -696,7 +706,9 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Vyvolat chybu u výrazů a deklarací s implikovaným typem any", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Vyvolá chybu u výrazů this s implikovaným typem any.", "Redirect_output_structure_to_the_directory_6006": "Přesměrování výstupní struktury do adresáře", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Odkazovaný projekt {0} musí mít nastavení \"composite\": true.", "Remove_declaration_for_Colon_0_90004": "Odebrat deklaraci pro {0}", + "Remove_destructuring_90009": "Odebrat destrukci", "Remove_import_from_0_90005": "Odebrat import z {0}", "Replace_import_with_0_95015": "Nahradí import použitím: {0}.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Oznámí se chyba, když některé cesty kódu ve funkci nevracejí hodnotu.", diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index b1f0d147886..e017d024e7c 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -4257,6 +4257,12 @@ + + + + + + @@ -4275,6 +4281,12 @@ + + + + + + diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 76872e0c298..cf58a0e20fd 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Todas las declaraciones de '{0}' deben tener modificadores idénticos.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Todas las declaraciones de '{0}' deben tener parámetros de tipo idénticos.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas las declaraciones de un método abstracto deben ser consecutivas.", + "All_destructured_elements_are_unused_6198": "Todos los elementos desestructurados están sin utilizar.", "All_imports_in_import_declaration_are_unused_6192": "Todas las importaciones de la declaración de importación están sin utilizar.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permitir las importaciones predeterminadas de los módulos sin exportación predeterminada. Esto no afecta a la emisión de código, solo a la comprobación de tipos.", "Allow_javascript_files_to_be_compiled_6102": "Permitir que se compilen los archivos de JavaScript.", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "No se puede invocar un objeto que es posiblemente \"null\".", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "No se puede invocar un objeto que es posiblemente \"null\" o \"no definido\".", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "No se puede invocar un objeto que es posiblemente \"no definido\".", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "No se puede anteponer el proyecto \"{0}\" porque no se ha establecido \"outFile\".", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "No se puede volver a exportar un tipo si se proporciona la marca \"--isolatedModules\".", "Cannot_read_file_0_Colon_1_5012": "No se puede leer el archivo \"{0}\": {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "No se puede volver a declarar la variable con ámbito de bloque '{0}'.", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila el proyecto teniendo en cuenta la ruta de acceso a su archivo de configuración o a una carpeta con un archivo \"tsconfig.json\".", "Compiler_option_0_expects_an_argument_6044": "La opción '{0}' del compilador espera un argumento.", "Compiler_option_0_requires_a_value_of_type_1_5024": "La opción '{0}' del compilador requiere un valor de tipo {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Los proyectos compuestos no pueden deshabilitar la emisión de declaración.", "Computed_property_names_are_not_allowed_in_enums_1164": "No se permiten nombres de propiedad calculada en las enumeraciones.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "No se permiten valores calculados en una enumeración que tiene miembros con valores de cadena.", "Concatenate_and_emit_output_to_single_file_6001": "Concatenar y emitir la salida en un único archivo.", @@ -328,8 +331,8 @@ "Duplicate_label_0_1114": "Etiqueta \"{0}\" duplicada.", "Duplicate_number_index_signature_2375": "Signatura de índice de número duplicada.", "Duplicate_string_index_signature_2374": "Signatura de índice de cadena duplicada.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "No se puede utilizar la importación dinámica cuando se destina a módulos ECMAScript 2015.", "Dynamic_import_cannot_have_type_arguments_1326": "La importación dinámica no puede tener argumentos de tipo", + "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_import_must_have_one_specifier_as_an_argument_1324": "La importación dinámica debe tener un especificador como argumento.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "El especificador de la importación dinámica debe ser de tipo \"string\", pero aquí tiene el tipo \"{0}\".", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "El elemento tiene un tipo 'any' implícito porque la expresión de índice no es de tipo 'number'.", @@ -338,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emitir un solo archivo con mapas de origen en lugar de tener un archivo aparte.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emitir el origen junto a los mapas de origen en un solo archivo; requiere que se establezca \"--inlineSourceMap\" o \"--sourceMap\".", "Enable_all_strict_type_checking_options_6180": "Habilitar todas las opciones de comprobación de tipos estricta.", + "Enable_project_compilation_6302": "Habilitar la compilación de proyecto", "Enable_strict_checking_of_function_types_6186": "Habilite la comprobación estricta de los tipos de función.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite la comprobación estricta de inicialización de propiedades en las clases.", "Enable_strict_null_checks_6113": "Habilitar comprobaciones estrictas de elementos nulos.", @@ -399,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "El archivo \"{0}\" tiene una extensión no admitida, así que se omitirá.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "La extensión del archivo '{0}' no es compatible. Las únicas extensiones compatibles son {1}.", "File_0_is_not_a_module_2306": "El archivo '{0}' no es un módulo.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "El archivo \"{0}\" no está en la lista de archivos del proyecto. Los proyectos deben enumerar todos los archivos o usar un patrón \"include\".", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "El archivo '{0}' no está en \"rootDir\" '{1}'. Se espera que \"rootDir\" contenga todos los archivos de origen.", "File_0_not_found_6053": "Archivo '{0}' no encontrado.", "File_change_detected_Starting_incremental_compilation_6032": "Se detectó un cambio de archivo. Iniciando la compilación incremental...", @@ -463,7 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "En las declaraciones de enumeración de ambiente, el inicializador de miembro debe ser una expresión constante.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "En una enumeración con varias declaraciones, solo una declaración puede omitir un inicializador para el primer elemento de la enumeración.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "El inicializador de miembro de las declaraciones de enumeración \"const\" debe ser una expresión constante.", - "Include_modules_imported_with_json_extension_6197": "Include modules imported with '.json' extension", + "Include_modules_imported_with_json_extension_6197": "Incluir módulos importados con la extensión \".json\"", "Index_signature_in_type_0_only_permits_reading_2542": "La signatura de índice del tipo '{0}' solo permite lectura.", "Index_signature_is_missing_in_type_0_2329": "Falta la signatura de índice en el tipo '{0}'.", "Index_signatures_are_incompatible_2330": "Las signaturas de índice no son compatibles.", @@ -603,9 +608,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "La opción \"isolatedModules\" solo se puede usar cuando se proporciona la opción \"--module\" o si la opción \"target\" es \"ES2015\" o una versión posterior.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "La opción 'paths' no se puede usar sin especificar la opción '--baseUrl'.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "La opción \"project\" no se puede combinar con archivos de origen en una línea de comandos.", - "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "No se puede especificar la opción \"--resolveJsonModule\" sin la estrategia de resolución de módulos \"node\".", "Options_Colon_6027": "Opciones:", "Output_directory_for_generated_declaration_files_6166": "Directorio de salida para los archivos de declaración generados.", + "Output_file_0_from_project_1_does_not_exist_6309": "El archivo de salida \"{0}\" del proyecto \"{1}\" no existe.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "El archivo de salida \"{0}\" no se compiló desde el archivo de origen \"{1}\".", "Overload_signature_is_not_compatible_with_function_implementation_2394": "La signatura de sobrecarga no es compatible con la implementación de función.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Las signaturas de sobrecarga deben ser todas abstractas o no abstractas.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Las signaturas de sobrecarga deben ser todas de ambiente o de no ambiente.", @@ -649,6 +656,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimir los nombres de los archivos generados que forman parte de la compilación.", "Print_the_compiler_s_version_6019": "Imprima la versión del compilador.", "Print_this_message_6017": "Imprima este mensaje.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Las referencias del proyecto no pueden formar un gráfico circular. Ciclo detectado: {0}", + "Projects_to_reference_6300": "Proyectos a los que se hará referencia", "Property_0_does_not_exist_on_const_enum_1_2479": "La propiedad '{0}' no existe en la enumeración 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "La propiedad '{0}' no existe en el tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "La propiedad \"{0}\" no existe en el tipo \"{1}\". ¿Olvidó usar \"await\"?", @@ -696,7 +705,9 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Generar un error en las expresiones y las declaraciones con un tipo \"any\" implícito.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Generar un error en expresiones 'this' con un tipo 'any' implícito.", "Redirect_output_structure_to_the_directory_6006": "Redirija la estructura de salida al directorio.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "El proyecto \"{0}\" al que se hace referencia debe tener el valor \"composite\": true.", "Remove_declaration_for_Colon_0_90004": "Quitar declaración de: \"{0}\"", + "Remove_destructuring_90009": "Quitar la desestructuración", "Remove_import_from_0_90005": "Quitar importación de \"{0}\"", "Replace_import_with_0_95015": "Reemplazar importación por \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Notificar un error cuando no todas las rutas de acceso de código en funcionamiento devuelven un valor.", diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json index 4f901fce171..2a95c4fe47b 100644 --- a/lib/fr/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Toutes les déclarations de '{0}' doivent avoir des modificateurs identiques.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Toutes les déclarations de '{0}' doivent avoir des paramètres de type identiques.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Toutes les déclarations d'une méthode abstraite doivent être consécutives.", + "All_destructured_elements_are_unused_6198": "Tous les éléments déstructurés sont inutilisés.", "All_imports_in_import_declaration_are_unused_6192": "Les importations de la déclaration d'importation ne sont pas toutes utilisées.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Autorisez les importations par défaut à partir des modules sans exportation par défaut. Cela n'affecte pas l'émission du code, juste le contrôle de type.", "Allow_javascript_files_to_be_compiled_6102": "Autorisez la compilation des fichiers JavaScript.", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Impossible d'appeler un objet qui a éventuellement une valeur 'null'.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Impossible d'appeler un objet qui a éventuellement une valeur 'null' ou 'undefined'.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Impossible d'appeler un objet qui a éventuellement une valeur 'undefined'.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Impossible de préfixer le projet '{0}', car 'outFile' n'est pas défini", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Impossible de réexporter un type quand l'indicateur '--isolatedModules' est spécifié.", "Cannot_read_file_0_Colon_1_5012": "Impossible de lire le fichier '{0}' : {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Impossible de redéclarer la variable de portée de bloc '{0}'.", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compilez le projet en fonction du chemin de son fichier config ou d'un dossier contenant 'tsconfig.json'.", "Compiler_option_0_expects_an_argument_6044": "L'option de compilateur '{0}' attend an argument.", "Compiler_option_0_requires_a_value_of_type_1_5024": "L'option de compilateur '{0}' exige une valeur de type {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Les projets composites ne doivent pas désactiver l'émission de déclaration.", "Computed_property_names_are_not_allowed_in_enums_1164": "Les noms de propriétés calculées ne sont pas autorisés dans les enums.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Les valeurs calculées ne sont pas autorisées dans un enum avec des membres ayant une valeur de chaîne.", "Concatenate_and_emit_output_to_single_file_6001": "Concaténer la sortie et l'émettre vers un seul fichier.", @@ -328,8 +331,8 @@ "Duplicate_label_0_1114": "Étiquette '{0}' en double.", "Duplicate_number_index_signature_2375": "Signature d'index de nombre dupliquée.", "Duplicate_string_index_signature_2374": "Signature d'index de chaîne dupliquée.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "L'importation dynamique ne peut pas être utilisée pour cibler des modules ECMAScript 2015.", "Dynamic_import_cannot_have_type_arguments_1326": "L'importation dynamique ne peut pas avoir d'arguments de type", + "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_import_must_have_one_specifier_as_an_argument_1324": "L'importation dynamique doit avoir un seul spécificateur comme argument.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Le spécificateur de l'importation dynamique doit être de type 'string', mais ici il est de type '{0}'.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "L'élément possède implicitement un type 'any', car l'expression d'index n'est pas de type 'number'.", @@ -338,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Émettez un seul fichier avec des mappages de sources au lieu d'avoir un fichier distinct.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Émettez la source aux côtés des mappages de sources dans un fichier unique. Nécessite la définition de '--inlineSourceMap' ou '--sourceMap'.", "Enable_all_strict_type_checking_options_6180": "Activez toutes les options de contrôle de type strict.", + "Enable_project_compilation_6302": "Activer la compilation du projet", "Enable_strict_checking_of_function_types_6186": "Activez la vérification stricte des types de fonction.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Activez la vérification stricte de l'initialisation des propriétés dans les classes.", "Enable_strict_null_checks_6113": "Activez strict null checks.", @@ -399,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Le fichier '{0}' a une extension non prise en charge. Il est ignoré.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Le fichier '{0}' possède une extension non prise en charge. Les seules extensions prises en charge sont {1}.", "File_0_is_not_a_module_2306": "Le fichier '{0}' n'est pas un module.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Le fichier '{0}' ne figure pas dans la liste de fichiers projet. Les projets doivent lister tous les fichiers ou utiliser un modèle 'include'.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Le fichier '{0}' ne se trouve pas sous 'rootDir' '{1}'. 'rootDir' est supposé contenir tous les fichiers sources.", "File_0_not_found_6053": "Fichier '{0}' introuvable.", "File_change_detected_Starting_incremental_compilation_6032": "Modification de fichier détectée. Démarrage de la compilation incrémentielle...", @@ -463,7 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Dans les déclarations d'enums ambiants, l'initialiseur de membre doit être une expression constante.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Dans un enum avec plusieurs déclarations, seule une déclaration peut omettre un initialiseur pour son premier élément d'enum.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Dans les déclarations d'enum 'const', l'initialiseur de membre doit être une expression constante.", - "Include_modules_imported_with_json_extension_6197": "Include modules imported with '.json' extension", + "Include_modules_imported_with_json_extension_6197": "Inclure les modules importés avec l'extension '.json'", "Index_signature_in_type_0_only_permits_reading_2542": "La signature d'index du type '{0}' autorise uniquement la lecture.", "Index_signature_is_missing_in_type_0_2329": "Signature d'index manquante dans le type '{0}'.", "Index_signatures_are_incompatible_2330": "Les signatures d'index sont incompatibles.", @@ -562,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Le nom de module '{0}' a été correctement résolu en '{1}'. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Le genre de résolution de module n'est pas spécifié. Utilisation de '{0}'.", "Module_resolution_using_rootDirs_has_failed_6111": "Échec de la résolution de module à l'aide de 'rootDirs'.", + "Move_to_a_new_file_95049": "Move to a new file", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Les séparateurs numériques consécutifs multiples ne sont pas autorisés.", "Multiple_constructor_implementations_are_not_allowed_2392": "Les implémentations de plusieurs constructeurs ne sont pas autorisées.", "NEWLINE_6061": "NOUVELLE LIGNE", @@ -603,9 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "L'option 'isolatedModules' peut être utilisée seulement quand l'option '--module' est spécifiée, ou quand l'option 'target' a la valeur 'ES2015' ou une version supérieure.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Impossible d'utiliser l'option 'paths' sans spécifier l'option '--baseUrl'.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Impossible d'associer l'option 'project' à des fichiers sources sur une ligne de commande.", - "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Impossible de spécifier l'option '--resolveJsonModule' sans la stratégie de résolution de module 'node'.", "Options_Colon_6027": "Options :", "Output_directory_for_generated_declaration_files_6166": "Répertoire de sortie pour les fichiers de déclaration générés.", + "Output_file_0_from_project_1_does_not_exist_6309": "Le fichier de sortie '{0}' du projet '{1}' n'existe pas", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Le fichier de sortie '{0}' n'a pas été créé à partir du fichier source '{1}'.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "La signature de surcharge n'est pas compatible avec l'implémentation de fonction.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Les signatures de surcharge doivent toutes être abstraites ou non abstraites.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Les signatures de surcharge doivent toutes être ambiantes ou non ambiantes.", @@ -649,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimez les noms des fichiers générés faisant partie de la compilation.", "Print_the_compiler_s_version_6019": "Affichez la version du compilateur.", "Print_this_message_6017": "Imprimez ce message.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Les références de projet ne peuvent pas former un graphe circulaire. Cycle détecté : {0}", + "Projects_to_reference_6300": "Projets à référencer", "Property_0_does_not_exist_on_const_enum_1_2479": "La propriété '{0}' n'existe pas sur l'enum 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "La propriété '{0}' n'existe pas sur le type '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "La propriété '{0}' n'existe pas sur le type '{1}'. Avez-vous oublié d'utiliser 'await' ?", @@ -696,7 +706,9 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Lever une erreur sur les expressions et les déclarations ayant un type 'any' implicite.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Déclenche une erreur sur les expressions 'this' avec un type 'any' implicite.", "Redirect_output_structure_to_the_directory_6006": "Rediriger la structure de sortie vers le répertoire.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Le projet référencé '{0}' doit avoir le paramètre \"composite\" avec la valeur true.", "Remove_declaration_for_Colon_0_90004": "Supprimer la déclaration pour : '{0}'", + "Remove_destructuring_90009": "Supprimer la déstructuration", "Remove_import_from_0_90005": "Supprimer l'importation de '{0}'", "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.", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index 3fe9c15ceab..00a24a5c852 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' のすべての宣言には、同一の修飾子が必要です。", "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' のすべての宣言には、同一の型パラメーターがある必要があります。", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象メソッドの宣言はすべて連続している必要があります。", + "All_destructured_elements_are_unused_6198": "非構造化要素はいずれも使用されていません。", "All_imports_in_import_declaration_are_unused_6192": "インポート宣言内のインポートはすべて未使用です。", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "既定のエクスポートがないモジュールからの既定のインポートを許可します。これは、型チェックのみのため、コード生成には影響を与えません。", "Allow_javascript_files_to_be_compiled_6102": "javascript ファイルのコンパイルを許可します。", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null' の可能性があるオブジェクトを呼び出すことはできません。", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null' または 'undefined' の可能性があるオブジェクトを呼び出すことはできません。", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'undefined' の可能性があるオブジェクトを呼び出すことはできません。", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'outFile' が設定されていないため、プロジェクト '{0}' を先頭に追加することはできません", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "0'--isolatedModules' フラグが指定されている場合、型を再エクスポートできません。", "Cannot_read_file_0_Colon_1_5012": "ファイル '{0}' を読み取れません: {1}。", "Cannot_redeclare_block_scoped_variable_0_2451": "ブロック スコープの変数 '{0}' を再宣言することはできません。", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "構成ファイルか、'tsconfig.json' を含むフォルダーにパスが指定されたプロジェクトをコンパイルします。", "Compiler_option_0_expects_an_argument_6044": "コンパイラ オプション '{0}' には引数が必要です。", "Compiler_option_0_requires_a_value_of_type_1_5024": "コンパイラ オプション '{0}' には {1} の型の値が必要です。", + "Composite_projects_may_not_disable_declaration_emit_6304": "複合プロジェクトで宣言の生成を無効にすることはできません。", "Computed_property_names_are_not_allowed_in_enums_1164": "計算されたプロパティ名は列挙型では使用できません。", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "文字列値のメンバーを持つ列挙型では、計算値は許可されません。", "Concatenate_and_emit_output_to_single_file_6001": "出力を連結して 1 つのファイルを生成します。", @@ -328,8 +331,8 @@ "Duplicate_label_0_1114": "ラベル '{0}' が重複しています。", "Duplicate_number_index_signature_2375": "number インデックス シグネチャが重複しています。", "Duplicate_string_index_signature_2374": "string インデックス シグネチャが重複しています。", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "ECMAScript 2015 モジュールを対象とする場合、動的インポートを使用することはできません。", "Dynamic_import_cannot_have_type_arguments_1326": "動的インポートには型引数を指定することはできません", + "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_import_must_have_one_specifier_as_an_argument_1324": "動的インポートには、引数として 1 つの指定子を指定する必要があります。", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "動的インポートの指定子の型は 'string' である必要がありますが、ここでは型 '{0}' が指定されています。", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "インデックス式が型 'number' ではないため、要素に 'any' 型が暗黙的に指定されます。", @@ -338,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "個々のファイルを持つ代わりに、複数のソース マップを含む単一ファイルを生成します。", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "単一ファイル内で sourcemap と共にソースを生成します。'--inlineSourceMap' または '--sourceMap' を設定する必要があります。", "Enable_all_strict_type_checking_options_6180": "厳密な型チェックのオプションをすべて有効にします。", + "Enable_project_compilation_6302": "プロジェクトのコンパイルを有効にします", "Enable_strict_checking_of_function_types_6186": "関数の型の厳密なチェックを有効にします。", "Enable_strict_checking_of_property_initialization_in_classes_6187": "クラス内のプロパティの初期化の厳密なチェックを有効にします。", "Enable_strict_null_checks_6113": "厳格な null チェックを有効にします。", @@ -399,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "ファイル '{0}' にはサポートされていない拡張機能があるため、スキップしています。", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "ファイル '{0}' はサポートされていない拡張子を含んでいます。サポートされている拡張子は {1} のみです。", "File_0_is_not_a_module_2306": "ファイル '{0}' はモジュールではありません。", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "ファイル '{0}' がプロジェクト ファイル リストに含まれていません。プロジェクトではすべてのファイルをリストするか、'include' パターンを使用する必要があります。", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "ファイル '{0}' が 'rootDir' '{1}' の下にありません。'rootDir' にすべてにソース ファイルが含まれている必要があります。", "File_0_not_found_6053": "ファイル '{0}' が見つかりません。", "File_change_detected_Starting_incremental_compilation_6032": "ファイルの変更が検出されました。インクリメンタル コンパイルを開始しています...", @@ -463,7 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "アンビエント列挙型の宣言では、メンバー初期化子は定数式である必要があります。", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "複数の宣言がある列挙型で、最初の列挙要素の初期化子を省略できる宣言は 1 つのみです。", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' 列挙型の宣言で、メンバー初期化子は定数式でなければなりません。", - "Include_modules_imported_with_json_extension_6197": "Include modules imported with '.json' extension", + "Include_modules_imported_with_json_extension_6197": "'.json' 拡張子付きのインポートされたモジュールを含める", "Index_signature_in_type_0_only_permits_reading_2542": "型 '{0}' のインデックス シグネチャは、読み取りのみを許可します。", "Index_signature_is_missing_in_type_0_2329": "型 '{0}' のインデックス シグネチャがありません。", "Index_signatures_are_incompatible_2330": "インデックスの署名に互換性がありません。", @@ -562,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== モジュール名 '{0}' が正常に '{1}' に解決されました。========", "Module_resolution_kind_is_not_specified_using_0_6088": "モジュール解決の種類が '{0}' を使用して指定されていません。", "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs' を使用したモジュール解決が失敗しました。", + "Move_to_a_new_file_95049": "Move to a new file", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "複数の連続した数値区切り記号を指定することはできません。", "Multiple_constructor_implementations_are_not_allowed_2392": "コンストラクターを複数実装することはできません。", "NEWLINE_6061": "改行", @@ -603,9 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "オプション 'isolatedModules' は、オプション '--module' が指定されているか、オプション 'target' が 'ES2015' 以上であるかのいずれかの場合でのみ使用できます。", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "オプション 'paths' は、'--baseUrl' オプションを指定せずに使用できません。", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "オプション 'project' をコマンド ライン上でソース ファイルと一緒に指定することはできません。", - "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "'node' モジュールの解決方法を使用せずにオプション '--resolveJsonModule' を指定することはできません。", "Options_Colon_6027": "オプション:", "Output_directory_for_generated_declaration_files_6166": "生成された宣言ファイルの出力ディレクトリ。", + "Output_file_0_from_project_1_does_not_exist_6309": "プロジェクト '{1}' からの出力ファイル '{0}' がありません", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "出力ファイル '{0}' はソース ファイル '{1}' からビルドされていません。", "Overload_signature_is_not_compatible_with_function_implementation_2394": "オーバーロード シグネチャは関数の実装に対応していません。", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "オーバーロードのシグネチャはすべてが抽象または非抽象である必要があります。", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "オーバーロードのシグネチャは、すべてアンビエントであるか、すべてアンビエントでないかのどちらかである必要があります。", @@ -649,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "コンパイルの一環として生成されたファイル名を書き出します。", "Print_the_compiler_s_version_6019": "コンパイラのバージョンを表示します。", "Print_this_message_6017": "このメッセージを表示します。", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "プロジェクト参照が円グラフを形成できません。循環が検出されました: {0}", + "Projects_to_reference_6300": "参照するプロジェクト", "Property_0_does_not_exist_on_const_enum_1_2479": "プロパティ '{0}' が 'const' 列挙型 '{1}' に存在しません。", "Property_0_does_not_exist_on_type_1_2339": "プロパティ '{0}' は型 '{1}' に存在しません。", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "型 '{1}' にプロパティ '{0}' は存在しません。'await' を使用していない可能性があります。", @@ -696,7 +706,9 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "暗黙的な 'any' 型を含む式と宣言に関するエラーを発生させます。", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "暗黙的な 'any' 型を持つ 'this' 式でエラーが発生します。", "Redirect_output_structure_to_the_directory_6006": "ディレクトリへ出力構造をリダイレクトします。", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "参照されているプロジェクト '{0}' には、設定 \"composite\": true が必要です。", "Remove_declaration_for_Colon_0_90004": "次に対する宣言を削除する: '{0}'", + "Remove_destructuring_90009": "非構造化を削除します", "Remove_import_from_0_90005": "'{0}' からのインポートを削除", "Replace_import_with_0_95015": "インポートを '{0}' に置換します。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "関数の一部のコード パスが値を返さない場合にエラーを報告します。", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index cd0513c8c0e..a217bd9c3e5 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -117,7 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}'의 모든 선언에는 동일한 한정자가 있어야 합니다.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}'의 모든 선언에는 동일한 형식 매개 변수가 있어야 합니다.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "추상 메서드의 모든 선언은 연속적이어야 합니다.", - "All_destructured_elements_are_unused_6198": "All destructured elements are unused.", + "All_destructured_elements_are_unused_6198": "구조 파괴된 요소가 모두 사용되지 않습니다.", "All_imports_in_import_declaration_are_unused_6192": "가져오기 선언의 모든 가져오기가 사용되지 않습니다.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "기본 내보내기가 없는 모듈에서 기본 가져오기를 허용합니다. 여기서는 코드 내보내기에는 영향을 주지 않고 형식 검사만 합니다.", "Allow_javascript_files_to_be_compiled_6102": "Javascript 파일을 컴파일하도록 허용합니다.", @@ -221,7 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null'일 수 있는 개체를 호출할 수 없습니다.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null'이거나 '정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", - "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Cannot prepend project '{0}' because it does not have 'outFile' set", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'outFile' 집합이 없기 때문에 '{0}' 프로젝트를 추가할 수 없습니다.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' 플래그가 제공된 경우 형식을 다시 내보낼 수 없습니다.", "Cannot_read_file_0_Colon_1_5012": "파일 '{0}'을(를) 읽을 수 없습니다. {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "블록 범위 변수 '{0}'을(를) 다시 선언할 수 없습니다.", @@ -262,7 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "구성 파일에 대한 경로 또는 'tsconfig.json'이 포함된 폴더에 대한 경로를 고려하여 프로젝트를 컴파일합니다.", "Compiler_option_0_expects_an_argument_6044": "컴파일러 옵션 '{0}'에는 인수가 필요합니다.", "Compiler_option_0_requires_a_value_of_type_1_5024": "컴파일러 옵션 '{0}'에 {1} 형식의 값이 필요합니다.", - "Composite_projects_may_not_disable_declaration_emit_6304": "Composite projects may not disable declaration emit.", + "Composite_projects_may_not_disable_declaration_emit_6304": "복합 프로젝트는 선언 내보내기를 사용하지 않도록 설정할 수 없습니다.", "Computed_property_names_are_not_allowed_in_enums_1164": "컴퓨팅된 속성 이름은 열거형에 사용할 수 없습니다.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "계산된 값은 문자열 값 멤버가 포함된 열거형에서 허용되지 않습니다.", "Concatenate_and_emit_output_to_single_file_6001": "출력을 연결하고 단일 파일로 내보냅니다.", @@ -331,8 +331,8 @@ "Duplicate_label_0_1114": "중복된 레이블 '{0}'입니다.", "Duplicate_number_index_signature_2375": "중복 숫자 인덱스 시그니처입니다.", "Duplicate_string_index_signature_2374": "중복 문자열 인덱스 시그니처입니다.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "ECMAScript 2015 모듈을 대상을 지정할 때에는 동적 가져오기를 사용할 수 없습니다.", "Dynamic_import_cannot_have_type_arguments_1326": "동적 가져오기에는 형식 인수를 사용할 수 없습니다.", + "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_import_must_have_one_specifier_as_an_argument_1324": "동적 가져오기에는 지정자 하나를 인수로 사용해야 합니다.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "동적 가져오기의 지정자는 'string' 형식이어야 하지만 여기에서 형식은 '{0}'입니다.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "인덱스 식이 'number' 형식이 아니므로 요소에 암시적으로 'any' 형식이 있습니다.", @@ -341,7 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "별도의 파일을 사용하는 대신 소스 맵과 함께 단일 파일을 내보냅니다.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "단일 파일 내에서 소스 맵과 함께 소스를 내보냅니다. '--inlineSourceMap' 또는 '--sourceMap'을 설정해야 합니다.", "Enable_all_strict_type_checking_options_6180": "엄격한 형식 검사 옵션을 모두 사용하도록 설정합니다.", - "Enable_project_compilation_6302": "Enable project compilation", + "Enable_project_compilation_6302": "프로젝트 컴파일을 사용하도록 설정", "Enable_strict_checking_of_function_types_6186": "함수 형식에 대한 엄격한 검사를 사용하도록 설정합니다.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "클래스의 속성 초기화에 대해 엄격한 검사를 사용하도록 설정합니다.", "Enable_strict_null_checks_6113": "엄격한 null 검사를 사용하도록 설정하세요.", @@ -403,7 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "'{0}' 파일은 확장명이 지원되지 않으므로 건너뜁니다.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "'{0}' 파일의 확장명이 지원되지 않습니다. 지원되는 확장명은 {1}뿐입니다.", "File_0_is_not_a_module_2306": "'{0}' 파일은 모듈이 아닙니다.", - "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "'{0}' 파일이 프로젝트 파일 목록에 없습니다. 프로젝트는 모든 파일을 나열하거나 'include' 패턴을 사용해야 합니다.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "'{0}' 파일이 'rootDir' '{1}' 아래에 있지 않습니다. 'rootDir'에는 모든 소스 파일이 포함되어 있어야 합니다.", "File_0_not_found_6053": "파일 '{0}'을(를) 찾을 수 없습니다.", "File_change_detected_Starting_incremental_compilation_6032": "파일 변경이 검색되었습니다. 증분 컴파일을 시작하는 중...", @@ -468,7 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "앰비언트 열거형 선언에서 멤버 이니셜라이저는 상수 식이어야 합니다.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "다중 선언이 포함된 열거형에서는 하나의 선언만 첫 번째 열거형 요소에 대한 이니셜라이저를 생략할 수 있습니다.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' 열거형 선언에서 멤버 이니셜라이저는 상수 식이어야 합니다.", - "Include_modules_imported_with_json_extension_6197": "Include modules imported with '.json' extension", + "Include_modules_imported_with_json_extension_6197": "'.json' 확장을 사용하여 가져온 모듈을 포함합니다.", "Index_signature_in_type_0_only_permits_reading_2542": "'{0}' 형식의 인덱스 시그니처는 읽기만 허용됩니다.", "Index_signature_is_missing_in_type_0_2329": "'{0}' 형식에 인덱스 시그니처가 없습니다.", "Index_signatures_are_incompatible_2330": "인덱스 시그니처가 호환되지 않습니다.", @@ -567,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== 모듈 이름 '{0}'이(가) '{1}'(으)로 확인되었습니다. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "모듈 확인 종류가 지정되지 않았습니다. '{0}'을(를) 사용합니다.", "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs'를 사용한 모듈 확인에 실패했습니다.", + "Move_to_a_new_file_95049": "Move to a new file", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "여러 개의 연속된 숫자 구분 기호는 허용되지 않습니다.", "Multiple_constructor_implementations_are_not_allowed_2392": "여러 생성자 구현은 허용되지 않습니다.", "NEWLINE_6061": "줄 바꿈", @@ -608,11 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "'isolatedModules' 옵션은 '--module' 옵션을 지정하거나 'target' 옵션이 'ES2015' 이상인 경우에만 사용할 수 있습니다.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "'paths' 옵션은 '--baseUrl' 옵션을 지정하지 않고 사용할 수 없습니다.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "명령줄에서 'project' 옵션을 원본 파일과 혼합하여 사용할 수 없습니다.", - "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "'node' 모듈 확인 전략 없이 '--resolveJsonModule' 옵션을 지정할 수 없습니다.", "Options_Colon_6027": "옵션:", "Output_directory_for_generated_declaration_files_6166": "생성된 선언 파일의 출력 디렉터리입니다.", - "Output_file_0_from_project_1_does_not_exist_6309": "Output file '{0}' from project '{1}' does not exist", - "Output_file_0_has_not_been_built_from_source_file_1_6305": "Output file '{0}' has not been built from source file '{1}'.", + "Output_file_0_from_project_1_does_not_exist_6309": "프로젝트 '{1}'의 출력 파일 '{0}'이(가) 존재하지 않습니다.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "출력 파일 '{0}'이(가) 소스 파일 '{1}'에서 빌드되지 않았습니다.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "오버로드 시그니처가 함수 구현과 호환되지 않습니다.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "오버로드 시그니처는 모두 추상이거나 비추상이어야 합니다.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "오버로드 시그니처는 모두 앰비언트이거나 앰비언트가 아니어야 합니다.", @@ -656,8 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "컴파일의 일부인 생성된 파일의 이름을 인쇄합니다.", "Print_the_compiler_s_version_6019": "컴파일러 버전을 인쇄합니다.", "Print_this_message_6017": "이 메시지를 출력합니다.", - "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Project references may not form a circular graph. Cycle detected: {0}", - "Projects_to_reference_6300": "Projects to reference", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "프로젝트 참조는 순환 그래프를 형성할 수 없습니다. 순환이 발견되었습니다. {0}", + "Projects_to_reference_6300": "참조할 프로젝트", "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 열거형 '{1}'에 '{0}' 속성이 없습니다.", "Property_0_does_not_exist_on_type_1_2339": "'{1}' 형식에 '{0}' 속성이 없습니다.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "속성 '{0}'이(가) '{1}' 형식에 없습니다. 'await' 사용을 잊으셨나요?", @@ -705,9 +706,9 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "암시된 'any' 형식이 있는 식 및 선언에서 오류를 발생합니다.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "암시된 'any' 형식이 있는 'this' 식에서 오류를 발생합니다.", "Redirect_output_structure_to_the_directory_6006": "출력 구조를 디렉터리로 리디렉션합니다.", - "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Referenced project '{0}' must have setting \"composite\": true.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "참조되는 프로젝트 '{0}'에는 \"composite\": true 설정이 있어야 합니다.", "Remove_declaration_for_Colon_0_90004": "'{0}'에 대한 선언 제거", - "Remove_destructuring_90009": "Remove destructuring", + "Remove_destructuring_90009": "구조 파괴 제거", "Remove_import_from_0_90005": "'{0}'에서 가져오기 제거", "Replace_import_with_0_95015": "가져오기를 '{0}'(으)로 바꿉니다.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "함수의 일부 코드 경로가 값을 반환하지 않는 경우 오류를 보고합니다.", diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index 94a83fc19b7..73d30a8ef26 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Wszystkie deklaracje elementu „{0}” muszą mieć identyczne modyfikatory.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Wszystkie deklaracje „{0}” muszą mieć identyczne parametry typu.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Wszystkie deklaracje metody abstrakcyjnej muszą występować obok siebie.", + "All_destructured_elements_are_unused_6198": "Wszystkie elementy, których strukturę usunięto, są nieużywane.", "All_imports_in_import_declaration_are_unused_6192": "Wszystkie importy w deklaracji importu są nieużywane.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Zezwalaj na domyślne importy z modułów bez domyślnego eksportu. To nie wpływa na emitowanie kodu, a tylko na sprawdzanie typów.", "Allow_javascript_files_to_be_compiled_6102": "Zezwalaj na kompilowanie plików JavaScript.", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „null”.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „null” lub „undefined”.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „undefined”.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Nie można poprzedzić projektu „{0}”, ponieważ nie ma on ustawionej właściwości „outFile”", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Nie można ponownie wyeksportować typu, jeśli podano flagę „--isolatedModules”", "Cannot_read_file_0_Colon_1_5012": "Nie można odczytać pliku „{0}”: {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Nie można ponownie zadeklarować zmiennej „{0}” o zakresie bloku.", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Skompiluj projekt z uwzględnieniem ścieżki jego pliku konfiguracji lub folderu z plikiem „tsconfig.json”.", "Compiler_option_0_expects_an_argument_6044": "Opcja kompilatora „{0}” oczekuje argumentu.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Opcja kompilatora „{0}” wymaga wartości typu {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Projekty kompozytowe nie mogą wyłączyć emitowania deklaracji.", "Computed_property_names_are_not_allowed_in_enums_1164": "Obliczone nazwy właściwości nie są dozwolone w wyliczeniach.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Obliczone wartości nie są dozwolone w wyliczeniu ze składowymi o wartości ciągu.", "Concatenate_and_emit_output_to_single_file_6001": "Połącz i wyemituj dane wyjściowe do pojedynczego pliku.", @@ -328,8 +331,8 @@ "Duplicate_label_0_1114": "Zduplikowana etykieta „{0}”.", "Duplicate_number_index_signature_2375": "Zduplikowana sygnatura indeksu liczbowego.", "Duplicate_string_index_signature_2374": "Zduplikowana sygnatura indeksu ciągu.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Nie można użyć dynamicznego importowania, gdy celem są moduły ECMAScript 2015.", "Dynamic_import_cannot_have_type_arguments_1326": "Dynamiczne importowanie nie może mieć argumentów typu", + "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_import_must_have_one_specifier_as_an_argument_1324": "Dynamiczne importowanie musi mieć jeden specyfikator jako argument.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specyfikator dynamicznego importowania musi być typu „string”, ale określono typ „{0}”.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Element niejawnie przyjmuje typ „any”, ponieważ wyrażenie indeksu ma typ inny niż „number”.", @@ -338,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emituj pojedynczy plik z mapami źródeł zamiast oddzielnego pliku.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emituj źródło razem z mapami źródłowymi w pojedynczym pliku; wymaga ustawienia opcji „--inlineSourceMap” lub „--sourceMap”.", "Enable_all_strict_type_checking_options_6180": "Włącz wszystkie opcje ścisłego sprawdzania typów.", + "Enable_project_compilation_6302": "Włącz kompilację projektu", "Enable_strict_checking_of_function_types_6186": "Włącz dokładne sprawdzanie typów funkcji.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Włącz dokładne sprawdzanie inicjowania właściwości w klasach.", "Enable_strict_null_checks_6113": "Włącz dokładne sprawdzanie wartości null.", @@ -399,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Plik „{0}” ma nieobsługiwane rozszerzenie, dlatego zostanie pominięty.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Plik „{0}” ma nieobsługiwane rozszerzenie. Obsługiwane są tylko rozszerzenia {1}.", "File_0_is_not_a_module_2306": "Plik „{0}” nie jest modułem.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Plik „{0}” nie znajduje się na liście plików projektu. Projekty muszą zawierać listę wszystkich plików lub używać wzorca „include”.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Plik „{0}” nie znajduje się w katalogu „rootDir” „{1}”. Katalog „rootDir” powinien zawierać wszystkie pliki źródłowe.", "File_0_not_found_6053": "Nie można odnaleźć pliku '{0}'.", "File_change_detected_Starting_incremental_compilation_6032": "Wykryto zmianę pliku. Trwa rozpoczynanie kompilacji przyrostowej...", @@ -463,7 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "W deklaracjach wyliczenia otoczenia inicjator składowej musi być wyrażeniem stałym.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "W przypadku wyliczenia z wieloma deklaracjami tylko jedna deklaracja może pominąć inicjator dla pierwszego elementu wyliczenia.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "W deklaracjach wyliczeń ze specyfikatorem „const” inicjator składowej musi być wyrażeniem stałym.", - "Include_modules_imported_with_json_extension_6197": "Include modules imported with '.json' extension", + "Include_modules_imported_with_json_extension_6197": "Uwzględnij moduły zaimportowane z rozszerzeniem „json”", "Index_signature_in_type_0_only_permits_reading_2542": "Sygnatura indeksu w typie „{0}” zezwala tylko na odczytywanie.", "Index_signature_is_missing_in_type_0_2329": "Brak sygnatury indeksu w typie „{0}”.", "Index_signatures_are_incompatible_2330": "Sygnatury indeksów są niezgodne.", @@ -603,9 +608,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Opcji „isolatedModules” można użyć tylko wtedy, gdy podano opcję „--module” lub opcja „target” określa cel „ES2015” lub wyższy.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Opcji „paths” nie można użyć bez podawania opcji „--baseUrl”.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Nie można mieszać opcji „project” z plikami źródłowymi w wierszu polecenia.", - "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Nie można określić opcji „--resolveJsonModule” bez strategii rozpoznawania modułów „node”.", "Options_Colon_6027": "Opcje:", "Output_directory_for_generated_declaration_files_6166": "Katalog wyjściowy dla wygenerowanych plików deklaracji.", + "Output_file_0_from_project_1_does_not_exist_6309": "Plik wyjściowy „{0}” z projektu „{1}” nie istnieje", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Plik wyjściowy „{0}” nie został utworzony na podstawie pliku źródłowego „{1}”.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "Sygnatura przeciążenia nie jest zgodna z implementacją funkcji.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Wszystkie sygnatury przeciążeń muszą być abstrakcyjne lub nieabstrakcyjne.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Wszystkie sygnatury przeciążeń muszą być otaczającymi sygnaturami lub żadna nie może być otaczającą sygnaturą.", @@ -649,6 +656,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Drukuj nazwy wygenerowanych plików będących częścią kompilacji.", "Print_the_compiler_s_version_6019": "Wypisz wersję kompilatora.", "Print_this_message_6017": "Wypisz ten komunikat.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odwołania do projektu nie mogą tworzyć grafu kołowego. Wykryto cykl: {0}", + "Projects_to_reference_6300": "Projekty do przywołania", "Property_0_does_not_exist_on_const_enum_1_2479": "Właściwość „{0}” nie istnieje w wyliczeniu ze specyfikatorem „const” „{1}”.", "Property_0_does_not_exist_on_type_1_2339": "Właściwość „{0}” nie istnieje w typie „{1}”.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Właściwość „{0}” nie istnieje w typie „{1}”. Czy zapomniano użyć elementu „await”?", @@ -696,7 +705,9 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Zgłaszaj błąd w przypadku wyrażeń i deklaracji z implikowanym typem „any”.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Zgłaszaj błąd w przypadku wyrażeń „this” z niejawnym typem „any”.", "Redirect_output_structure_to_the_directory_6006": "Przekieruj strukturę wyjściową do katalogu.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Przywoływany projekt „{0}” musi mieć ustawienie „composite” o wartości true.", "Remove_declaration_for_Colon_0_90004": "Usuń deklarację dla: „{0}”", + "Remove_destructuring_90009": "Usuń usuwanie struktury", "Remove_import_from_0_90005": "Usuń import z „{0}”", "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ść.", diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index ab843305983..653092b6b80 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Todas as declarações de '{0}' devem ter modificadores idênticos.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Todas as declarações de '{0}' devem ter parâmetros de tipo idênticos.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas as declarações de um método abstrato devem ser consecutivas.", + "All_destructured_elements_are_unused_6198": "Todos os elementos desestruturados são inutilizados.", "All_imports_in_import_declaration_are_unused_6192": "Nenhuma das importações na declaração de importação está sendo utilizada.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permita importações padrão de módulos sem exportação padrão. Isso não afeta a emissão do código, apenas a verificação de digitação.", "Allow_javascript_files_to_be_compiled_6102": "Permita que arquivos javascript sejam compilados.", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Não é possível invocar um objeto que é possivelmente 'nulo'.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Não é possível invocar um objeto que é possivelmente 'nulo' ou 'indefinido'.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Não é possível invocar um objeto que é possivelmente 'indefinido'.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Não é possível preceder o projeto '{0}' porque ele não tem o conjunto 'outFile'", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Não será possível reexportar um tipo quando o sinalizador '--isolatedModules' for fornecido.", "Cannot_read_file_0_Colon_1_5012": "Não é possível ler o arquivo '{0}': {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Não é possível declarar novamente a variável de escopo de bloco '{0}'.", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compile o projeto dando o caminho para seu arquivo de configuração ou para uma pasta com um 'tsconfig.json'.", "Compiler_option_0_expects_an_argument_6044": "A opção do compilador '{0}' espera um argumento.", "Compiler_option_0_requires_a_value_of_type_1_5024": "A opção do compilador '{0}' requer um valor do tipo {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Projetos compostos não podem desabilitar a emissão de declaração.", "Computed_property_names_are_not_allowed_in_enums_1164": "Nomes de propriedade calculados não são permitidos em enums.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Os valores computados não são permitidos em uma enumeração com membros de valor de cadeia de caracteres.", "Concatenate_and_emit_output_to_single_file_6001": "Concatenar e emitir saída para um arquivo único.", @@ -328,8 +331,8 @@ "Duplicate_label_0_1114": "Rótulo '{0}' duplicado.", "Duplicate_number_index_signature_2375": "Assinatura de índice de número duplicado.", "Duplicate_string_index_signature_2374": "Assinatura de índice de cadeia de caracteres duplicada.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "A importação dinâmica não pode ser usada ao destinar módulos de ECMAScript 2015.", "Dynamic_import_cannot_have_type_arguments_1326": "A importação dinâmica não pode ter argumentos de tipo", + "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_import_must_have_one_specifier_as_an_argument_1324": "A importação dinâmica deve ter um especificador como um argumento.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "O especificador da importação dinâmica deve ser do tipo 'string', mas aqui tem o tipo '{0}'.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "O elemento implicitamente tem um tipo 'any' porque a expressão de índice não é do tipo 'number'.", @@ -338,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emitir um arquivo único com os mapas de origem em vez de arquivos separados.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emitir a origem ao lado dos sourcemaps em um arquivo único; a definição requer '--inlineSourceMap' ou '--sourceMap'.", "Enable_all_strict_type_checking_options_6180": "Habilitar todas as opções estritas de verificação de tipo.", + "Enable_project_compilation_6302": "Habilitar a compilação do projeto", "Enable_strict_checking_of_function_types_6186": "Habilitar verificação estrita de tipos de função.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite a verificação estrita de inicialização de propriedade nas classes.", "Enable_strict_null_checks_6113": "Habilite verificações nulas estritas.", @@ -399,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "O arquivo '{0}' tem uma extensão sem suporte, portanto ele será ignorado.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "O arquivo '{0}' tem extensão sem suporte. As únicas extensões com suporte são {1}.", "File_0_is_not_a_module_2306": "O arquivo '{0}' não é um módulo.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "O arquivo '{0}' não está na lista de arquivos de projeto. Os projetos devem listar todos os arquivos ou usar um padrão 'include'.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "O arquivo '{0}' não está em 'rootDir' '{1}'. Espera-se que 'rootDir' contenha todos os arquivos de origem.", "File_0_not_found_6053": "Arquivo '{0}' não encontrado.", "File_change_detected_Starting_incremental_compilation_6032": "Alteração do arquivo detectada. Iniciando compilação incremental...", @@ -463,7 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Em declarações de enumeração de ambiente, o inicializador de membro deve ser uma expressão de constante.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Em uma enumeração com várias declarações, somente uma declaração pode omitir um inicializador para o primeiro elemento de enumeração.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Em declarações de enumeração 'const', o inicializador de membro deve ser uma expressão de constante.", - "Include_modules_imported_with_json_extension_6197": "Include modules imported with '.json' extension", + "Include_modules_imported_with_json_extension_6197": "Incluir módulos importados com a extensão '.json'", "Index_signature_in_type_0_only_permits_reading_2542": "Assinatura de índice no tipo '{0}' permite somente leitura.", "Index_signature_is_missing_in_type_0_2329": "Assinatura de índice ausente no tipo '{0}'.", "Index_signatures_are_incompatible_2330": "As assinaturas de índice são incompatíveis.", @@ -603,9 +608,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "A opção 'isolatedModules' só pode ser usada quando nenhuma opção de '--module' for fornecida ou a opção 'target' for 'ES2015' ou superior.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "A opção 'paths' não pode ser usada sem se especificar a opção '--baseUrl'.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "A opção 'project' não pode ser mesclada com arquivos de origem em uma linha de comando.", - "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "A opção '--resolveJsonModule' não pode ser especificada sem a estratégia de resolução de módulo de 'nó'.", "Options_Colon_6027": "Opções:", "Output_directory_for_generated_declaration_files_6166": "Diretório de saída para os arquivos de declaração gerados.", + "Output_file_0_from_project_1_does_not_exist_6309": "O arquivo de saída '{0}' do projeto '{1}' não existe", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "O arquivo de saída '{0}' não foi compilado do arquivo de origem '{1}'.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "A assinatura de sobrecarga não é compatível com a implementação da função.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Assinaturas de sobrecarga devem todas ser abstratas ou não abstratas.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Todas as assinaturas de sobrecarga devem ser ambiente ou não ambiente.", @@ -649,6 +656,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Nomes de impressão das partes dos arquivos gerados da compilação.", "Print_the_compiler_s_version_6019": "Imprima a versão do compilador.", "Print_this_message_6017": "Imprima esta mensagem.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Referências de projeto não podem formar um gráfico circular. Ciclo detectado: {0}", + "Projects_to_reference_6300": "Projetos para referência", "Property_0_does_not_exist_on_const_enum_1_2479": "A propriedade '{0}' não existe na enumeração 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "A propriedade '{0}' não existe no tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "A propriedade '{0}' não existe no tipo '{1}'. Você esqueceu de usar 'await'?", @@ -696,7 +705,9 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Gerar erro em expressões e declarações com um tipo 'any' implícito.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Gerar erro em expressões 'this' com um tipo 'any' implícito.", "Redirect_output_structure_to_the_directory_6006": "Redirecione a estrutura de saída para o diretório.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "O projeto referenciado '{0}' deve ter a configuração de \"composite\": true.", "Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'", + "Remove_destructuring_90009": "Remover desestruturação", "Remove_import_from_0_90005": "Remover importação do '{0}'", "Replace_import_with_0_95015": "Substitua a importação com '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Relate erro quando nem todos os caminhos de código na função retornarem um valor.", diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index 46b139d124c..e45d3c110bc 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Все объявления \"{0}\" должны иметь одинаковые модификаторы.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Все объявления \"{0}\" должны иметь одинаковые параметры типа.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Все объявления абстрактных методов должны быть последовательными.", + "All_destructured_elements_are_unused_6198": "Все деструктурированные элементы не используются.", "All_imports_in_import_declaration_are_unused_6192": "Ни один из импортов в объявлении импорта не используется.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Разрешить импорт по умолчанию из модулей без экспорта по умолчанию. Это не повлияет на выведение кода — только на проверку типов.", "Allow_javascript_files_to_be_compiled_6102": "Разрешить компиляцию файлов javascript.", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Не удается вызвать объект, который может иметь значение \"NULL\".", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Не удается вызвать объект, который может иметь значение \"NULL\" или \"undefined\".", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Не удается вызвать объект, который может иметь значение \"undefined\".", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Невозможно добавить проект \"{0}\" в начало, так как для него не задан outFile", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Невозможно повторно экспортировать тип, если установлен флажок \"--isolatedModules\".", "Cannot_read_file_0_Colon_1_5012": "Не удается считать файл \"{0}\": {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Невозможно повторно объявить переменную \"{0}\" с областью видимости \"Блок\".", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Компиляция проекта по заданному пути к файлу конфигурации или папке с файлом tsconfig.json.", "Compiler_option_0_expects_an_argument_6044": "Параметр компилятора \"{0}\" ожидает аргумент.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Параметр \"{0}\" компилятора требует значение типа {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Составные проекты не могут отключать выпуск объявления.", "Computed_property_names_are_not_allowed_in_enums_1164": "Имена вычисляемых свойств запрещены в перечислениях.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Вычисленные значения запрещены в перечислении с членами, имеющими строковые значения.", "Concatenate_and_emit_output_to_single_file_6001": "Связать и вывести результаты в один файл.", @@ -328,8 +331,8 @@ "Duplicate_label_0_1114": "Повторяющаяся метка \"{0}\".", "Duplicate_number_index_signature_2375": "Повторяющаяся сигнатура числового индекса.", "Duplicate_string_index_signature_2374": "Повторяющаяся сигнатура строкового индекса.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Динамический импорт не может использоваться с модулями ECMAScript 2015.", "Dynamic_import_cannot_have_type_arguments_1326": "При динамическом импорте не могут использоваться аргументы типов", + "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_import_must_have_one_specifier_as_an_argument_1324": "При динамическом импорте необходимо указать один описатель в качестве аргумента.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Описатель динамического импорта должен иметь тип \"string\", но имеет тип \"{0}\".", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Элемент неявно содержит тип any, так как выражение индекса не имеет тип number.", @@ -338,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Порождать один файл с сопоставлениями источников, а не создавать отдельный файл.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Порождать источник вместе с sourcemap в одном файле (нужно задать параметр --inlineSourceMap или --sourceMap).", "Enable_all_strict_type_checking_options_6180": "Включить все параметры строгой проверки типов.", + "Enable_project_compilation_6302": "Включить компиляцию проекта", "Enable_strict_checking_of_function_types_6186": "Включение строгой проверки типов функций.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Включение строгой проверки инициализации свойств в классах.", "Enable_strict_null_checks_6113": "Включить строгие проверки NULL.", @@ -399,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Файл \"{0}\" имеет неподдерживаемое разрешение, поэтому будет пропущен.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Файл \"{0}\" имеет неподдерживаемое расширение. Поддерживаются только следующие расширения: {1}.", "File_0_is_not_a_module_2306": "Файл \"{0}\" не является модулем.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Файл \"{0}\" отсутствует в списке файлов проекта. Проекты должны перечислять все файлы или использовать шаблон включения.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Файл \"{0}\" отсутствует в \"rootDir\" \"{1}\". Все исходные файлы должны находиться в каталоге \"rootDir\".", "File_0_not_found_6053": "Файл \"{0}\" не найден.", "File_change_detected_Starting_incremental_compilation_6032": "Обнаружено изменение в файле. Запускается инкрементная компиляция...", @@ -562,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Имя модуля \"{0}\" было успешно разрешено в \"{1}\". ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Тип разрешения модуля не указан, используется \"{0}\".", "Module_resolution_using_rootDirs_has_failed_6111": "Произошел сбой при разрешении модуля с помощью \"rootDirs\".", + "Move_to_a_new_file_95049": "Move to a new file", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Использовать несколько последовательных числовых разделителей запрещено.", "Multiple_constructor_implementations_are_not_allowed_2392": "Не разрешается использование нескольких реализаций конструкторов.", "NEWLINE_6061": "НОВАЯ СТРОКА", @@ -603,9 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Параметр isolatedModules можно использовать, только если указан параметр --module или если параметр target — ES2015 или выше.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Параметр paths невозможно использовать без указания параметра \"--baseUrl\".", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Параметр project не может быть указан вместе с исходными файлами в командной строке.", - "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Параметр \"--resolveJsonModule\" нельзя указать без стратегии разрешения модуля node.", "Options_Colon_6027": "Параметры:", "Output_directory_for_generated_declaration_files_6166": "Выходной каталог для создаваемых файлов объявления.", + "Output_file_0_from_project_1_does_not_exist_6309": "Выходной файл \"{0}\" из проекта \"{1}\" не существует", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Выходной файл \"{0}\" не создан из исходного файла \"{1}\".", "Overload_signature_is_not_compatible_with_function_implementation_2394": "Сигнатура перегрузки несовместима с реализацией функции.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Сигнатуры перегрузки должны быть абстрактными или неабстрактными.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Все сигнатуры перегрузки должны быть либо внешними, либо не внешними.", @@ -649,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Печатать имена создаваемых файлов, входящих в компиляцию.", "Print_the_compiler_s_version_6019": "Печать версии компилятора.", "Print_this_message_6017": "Напечатайте это сообщение.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Ссылки на проект не могут формировать циклический граф. Обнаружен цикл: {0}", + "Projects_to_reference_6300": "Проекты для ссылки", "Property_0_does_not_exist_on_const_enum_1_2479": "Свойство \"{0}\" не существует в перечислении const \"{1}\".", "Property_0_does_not_exist_on_type_1_2339": "Свойство \"{0}\" не существует в типе \"{1}\".", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Свойство \"{0}\" не существует в типе \"{1}\". Возможно, пропущено \"await\"?", @@ -696,7 +706,9 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Вызывать ошибку в выражениях и объявлениях с подразумеваемым типом any.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Вызвать ошибку в выражениях this с неявным типом any.", "Redirect_output_structure_to_the_directory_6006": "Перенаправить структуру вывода в каталог.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Referenced project '{0}' must have setting \"composite\": true.", "Remove_declaration_for_Colon_0_90004": "Удалите объявление: \"{0}\"", + "Remove_destructuring_90009": "Удалить деструктурирование", "Remove_import_from_0_90005": "Удалить импорт из \"{0}\"", "Replace_import_with_0_95015": "Замена импорта на \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути кода в функции возвращают значение.", diff --git a/lib/tsc.js b/lib/tsc.js index 419236c1f64..b1b42bc90f6 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -1154,17 +1154,18 @@ var ts; } ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { + var _a; var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { result.push(map ? map(value) : value); } return result; - var _b; } ts.arrayFrom = arrayFrom; function forEachEntry(map, callback) { + var _a; var iterator = map.entries(); - for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { var key = pair[0], value = pair[1]; var result = callback(value, key); if (result) { @@ -1172,19 +1173,18 @@ var ts; } } return undefined; - var _b; } ts.forEachEntry = forEachEntry; function forEachKey(map, callback) { + var _a; var iterator = map.keys(); - for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { var result = callback(key); if (result) { return result; } } return undefined; - var _b; } ts.forEachKey = forEachKey; function copyEntries(source, target) { @@ -2840,12 +2840,12 @@ var ts; ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; ts.missingFileModifiedTime = new Date(0); function createPollingIntervalBasedLevels(levels) { + var _a; return _a = {}, _a[PollingInterval.Low] = levels.Low, _a[PollingInterval.Medium] = levels.Medium, _a[PollingInterval.High] = levels.High, _a; - var _a; } var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); @@ -4666,6 +4666,8 @@ var ts; Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), }; })(ts || (ts = {})); var ts; @@ -7815,6 +7817,10 @@ var ts; } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { case 243: case 249: @@ -7824,12 +7830,13 @@ var ts; case 186: return node.parent; case 177: - return ts.cast(node.parent.parent, ts.isImportTypeNode); + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: - return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + return undefined; } } - ts.importFromModuleSpecifier = importFromModuleSpecifier; + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { case 243: @@ -16132,6 +16139,7 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var _a; var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; @@ -16149,7 +16157,6 @@ var ts; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; - var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; function parseJSDocCommentWorker(start, length) { @@ -21863,6 +21870,7 @@ var ts; function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864) { + ts.Debug.assert(!!(target.flags & 33554432)); if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { target.constEnumOnlyModule = false; } @@ -21887,6 +21895,10 @@ var ts; var sourceInitializer = ts.getJSInitializerSymbol(source); var targetInitializer = ts.getJSInitializerSymbol(target); if (sourceInitializer !== source || targetInitializer !== target) { + if (!(targetInitializer.flags & 33554432)) { + var mergedInitializer = getMergedSymbol(targetInitializer); + targetInitializer = mergedInitializer === targetInitializer ? cloneSymbol(targetInitializer) : mergedInitializer; + } mergeSymbol(targetInitializer, sourceInitializer); } } @@ -36331,7 +36343,7 @@ var ts; checkGrammarForGenerator(node); } var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); if (isTypeAny(type)) { return type; } @@ -64604,6 +64616,7 @@ var ts; return !prevSignature || latestSignature !== prevSignature; } function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; var compilerOptions = programOfThisState.getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { return getAllFileNames(state, programOfThisState); @@ -64620,7 +64633,7 @@ var ts; var references = state.referencedMap.get(path); if (references) { var iterator = references.keys(); - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { queue.push(value); } } @@ -64630,7 +64643,6 @@ var ts; var file = programOfThisState.getSourceFileByPath(path); return file ? file.fileName : path; })); - var _b; } BuilderState.getAllDependencies = getAllDependencies; function getAllFileNames(state, programOfThisState) { @@ -65628,12 +65640,12 @@ var ts; watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, setTimeout: system.setTimeout ? (function (callback, ms) { + var _a; var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - var _a; }) : ts.noop, clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, trace: function (s) { return system.write(s); }, @@ -67641,6 +67653,7 @@ var ts; return extendedConfigPath; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -67668,7 +67681,6 @@ var ts; mapPropertiesInRawIfNotUndefined("files"); } return extendedConfig; - var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { diff --git a/lib/tsserver.js b/lib/tsserver.js index d30bc429a11..50e11fa3c57 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -5893,6 +5893,8 @@ var ts; Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), }; })(ts || (ts = {})); var ts; @@ -9042,6 +9044,10 @@ var ts; } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { case 243: case 249: @@ -9051,12 +9057,13 @@ var ts; case 186: return node.parent; case 177: - return ts.cast(node.parent.parent, ts.isImportTypeNode); + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: - return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + return undefined; } } - ts.importFromModuleSpecifier = importFromModuleSpecifier; + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { case 243: @@ -23300,6 +23307,7 @@ var ts; function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864) { + ts.Debug.assert(!!(target.flags & 33554432)); if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { target.constEnumOnlyModule = false; } @@ -23324,6 +23332,10 @@ var ts; var sourceInitializer = ts.getJSInitializerSymbol(source); var targetInitializer = ts.getJSInitializerSymbol(target); if (sourceInitializer !== source || targetInitializer !== target) { + if (!(targetInitializer.flags & 33554432)) { + var mergedInitializer = getMergedSymbol(targetInitializer); + targetInitializer = mergedInitializer === targetInitializer ? cloneSymbol(targetInitializer) : mergedInitializer; + } mergeSymbol(targetInitializer, sourceInitializer); } } @@ -37768,7 +37780,7 @@ var ts; checkGrammarForGenerator(node); } var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); if (isTypeAny(type)) { return type; } @@ -69915,6 +69927,9 @@ var ts; ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); return 2; } + else if (ts.isLiteralTypeNode(node.parent)) { + return 2 | 1; + } else { return 1; } @@ -73822,7 +73837,6 @@ var ts; function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { switch (triggerCharacter) { case ".": - case "/": case "@": return true; case '"': @@ -73831,6 +73845,10 @@ var ts; return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": return contextToken.kind === 27 && contextToken.parent.kind !== 199; + case "/": + return ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 41 && ts.isJsxClosingElement(contextToken.parent); default: return ts.Debug.assertNever(triggerCharacter); } @@ -74425,11 +74443,7 @@ var ts; } break; case 178: - if (direct.qualifier) { - directImports.push(direct); - } - else { - } + directImports.push(direct); break; default: ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); @@ -74504,7 +74518,12 @@ var ts; } if (decl.kind === 178) { if (decl.qualifier) { - singleReferences.push(decl.qualifier.kind === 71 ? decl.qualifier : decl.qualifier.right); + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2) { + singleReferences.push(decl.argument.literal); } return; } @@ -75029,7 +75048,7 @@ var ts; if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles, sourceFilesSet); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -75042,34 +75061,33 @@ var ts; if (!symbol) { return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } - if (symbol.flags & 1536 && isModuleReferenceLocation(node)) { - return getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet); + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export="); + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + symbol = ts.skipAlias(exportEquals, checker); + node = undefined; } - return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; - function isModuleReferenceLocation(node) { - if (!ts.isStringLiteralLike(node)) { - return false; - } - switch (node.parent.kind) { - case 238: - case 253: - case 243: - case 249: - return true; - case 177: - return ts.isImportTypeNode(node.parent.parent); - case 186: - return ts.isRequireCall(node.parent, false) || ts.isImportCall(node.parent); - default: - return false; - } + function isModuleSymbol(symbol) { + return symbol.flags & 1536 && ts.find(symbol.declarations, ts.isSourceFile); } - function getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet) { + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); - var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } return { type: "node", node: reference.literal }; } else { @@ -75094,7 +75112,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; + return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; } function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { @@ -75116,16 +75134,16 @@ var ts; return undefined; } function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; - var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); + symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7; var result = []; - var state = new State(sourceFiles, sourceFilesSet, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); - if (node.kind === 79) { + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0, checker, cancellationToken, searchMeaning, options, result); + if (node && node.kind === 79) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 }, state); } else { - var search = state.createSearch(node, symbol, undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + var search = state.createSearch(node, symbol, undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] }); var scope = getSymbolScope(symbol); if (scope) { getReferencesInContainer(scope, scope.getSourceFile(), search, state, !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); @@ -75204,7 +75222,7 @@ var ts; if (searchOptions === void 0) { searchOptions = {}; } var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; State.prototype.referenceAdder = function (searchSymbol) { @@ -75240,10 +75258,8 @@ var ts; var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; - if (hasMatchingMeaning(singleRef, state) && - !(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default")) { + if (shouldAddSingleReference(singleRef, state)) addRef(singleRef); - } } } for (var _b = 0, importSearches_1 = importSearches; _b < importSearches_1.length; _b++) { @@ -75270,6 +75286,15 @@ var ts; } } } + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + if (!ts.isIdentifier(singleRef)) + return false; + return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default"); + } function searchForImportedSymbol(symbol, state) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -77526,7 +77551,9 @@ var ts; ? defaultImports[0] : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 - ? undefined + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); @@ -77564,7 +77591,7 @@ var ts; }; } function compareIdentifiers(s1, s2) { - return ts.compareStringsCaseSensitive(s1.text, s2.text); + return ts.compareStringsCaseInsensitive(s1.text, s2.text); } } OrganizeImports.coalesceImports = coalesceImports; @@ -77576,7 +77603,7 @@ var ts; var name2 = getExternalModuleName(m2); return ts.compareBooleans(name1 === undefined, name2 === undefined) || ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || - ts.compareStringsCaseSensitive(name1, name2); + ts.compareStringsCaseInsensitive(name1, name2); } OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); @@ -78469,6 +78496,8 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 && symbol.parent.flags & 1536) { return undefined; } + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) + return undefined; var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -83506,7 +83535,7 @@ var ts; function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken, preferences) { var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; } @@ -83602,12 +83631,6 @@ var ts; return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); } } - function usesJsExtensionOnImports(sourceFile) { - return ts.firstDefined(sourceFile.imports, function (_a) { - var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js") : undefined; - }) || false; - } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -83621,232 +83644,14 @@ var ts; ts.Debug.assertNever(kind); } } - function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) { - var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(sourceFile); + function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; - }); + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program, sourceFile, host, preferences); return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); }); return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - function getAllModulePaths(program, _a) { - var fileName = _a.fileName; - var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === fileName ? res.originalPath : undefined; - }); - }); - return symlinks.length === 0 ? [fileName] : symlinks; - } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } - function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { - for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); - return key.replace("*", matchedStar); - } - } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; - } - } - } - } - function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { - return undefined; - } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName)); - } - } - } - function getNodeModulePathParts(fullPath) { - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1; - } - break; - case 1: - case 2: - if (state === 1 && fullPath.charAt(partStart + 1) === "@") { - state = 2; - } - else { - packageRootIndex = partEnd; - state = 3; - } - break; - case 3: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1; - } - else { - state = 3; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); - return isPathRelativeToParent(relativePath) ? undefined : relativePath; - }); - } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { - var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; - } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; - } - function isPathRelativeToParent(path) { - return ts.startsWith(path, ".."); - } function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) { var fromExistingImport = ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; @@ -83865,7 +83670,7 @@ var ts; var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences); + : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.host, ctx.preferences); for (var _i = 0, newImportInfos_1 = newImportInfos; _i < newImportInfos_1.length; _i++) { var info = newImportInfos_1[_i]; addNew.push(getCodeActionForNewImport(ctx, info)); @@ -84835,6 +84640,89 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, false); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + switch (container.kind) { + case 216: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements)); + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + break; + } + case 218: + case 219: + changes.deleteNode(sourceFile, container); + break; + default: + if (ts.isBlock(statement.parent)) { + split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); }); + } + else { + changes.deleteNode(sourceFile, statement); + } + } + } + function shouldRemove(s) { + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 | 2)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 235: + case 236: + return true; + case 238: + return ts.getModuleInstanceState(s) !== 1; + case 237: + return ts.hasModifier(s, 2048); + } + } + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + ts.Debug.assert(index !== -1); + return arr.slice(index); + } + function split(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + var value = arr[i]; + if (pred(value)) { + start = start || value; + } + else { + if (start) { + cb(start, arr[i - 1]); + start = undefined; + } + } + } + if (start) + cb(start, arr[arr.length - 1]); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -85852,6 +85740,243 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + var compilerOptions = program.getCompilerOptions(); + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var sourceDirectory = ts.getDirectoryPath(importingSourceFile.fileName); + return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } + var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js") : undefined; + }) || false; + } + function getAllModulePaths(program, _a) { + var fileName = _a.fileName; + var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + }); + }); + return symlinks.length === 0 ? [fileName] : symlinks; + } + function getRelativePathNParents(relativePath) { + var components = ts.getPathComponents(relativePath); + if (components[0] || components.length === 1) + return 0; + for (var i = 1; i < components.length; i++) { + if (components[i] !== "..") + return i - 1; + } + return components.length - 1; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { + var roots = ts.getEffectiveTypeRoots(options, host); + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; + } + } + } + } + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName)); + } + } + } + function getNodeModulePathParts(fullPath) { + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1; + } + break; + case 1: + case 2: + if (state === 1 && fullPath.charAt(partStart + 1) === "@") { + state = 2; + } + else { + packageRootIndex = partEnd; + state = 3; + } + break; + case 3: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1; + } + else { + state = 3; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + var noExtension = ts.removeFileExtension(fileName); + return addJsExtension + ? noExtension + ".js" + : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 767e6042d9a..26de30f325c 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -6735,6 +6735,8 @@ var ts; Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), }; })(ts || (ts = {})); var ts; @@ -10272,6 +10274,10 @@ var ts; } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { case 243 /* ImportDeclaration */: case 249 /* ExportDeclaration */: @@ -10281,12 +10287,13 @@ var ts; case 186 /* CallExpression */: return node.parent; case 177 /* LiteralType */: - return ts.cast(node.parent.parent, ts.isImportTypeNode); + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: - return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + return undefined; } } - ts.importFromModuleSpecifier = importFromModuleSpecifier; + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { case 243 /* ImportDeclaration */: @@ -27112,6 +27119,7 @@ var ts; function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864 /* JSContainer */) { + ts.Debug.assert(!!(target.flags & 33554432 /* Transient */)); // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { // reset flag when merging instantiated module into value module that has only const enums @@ -27139,6 +27147,10 @@ var ts; var sourceInitializer = ts.getJSInitializerSymbol(source); var targetInitializer = ts.getJSInitializerSymbol(target); if (sourceInitializer !== source || targetInitializer !== target) { + if (!(targetInitializer.flags & 33554432 /* Transient */)) { + var mergedInitializer = getMergedSymbol(targetInitializer); + targetInitializer = mergedInitializer === targetInitializer ? cloneSymbol(targetInitializer) : mergedInitializer; + } mergeSymbol(targetInitializer, sourceInitializer); } } @@ -44155,7 +44167,7 @@ var ts; checkGrammarForGenerator(node); } var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); if (isTypeAny(type)) { return type; } @@ -84265,6 +84277,10 @@ var ts; ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName return 2 /* Type */; } + else if (ts.isLiteralTypeNode(node.parent)) { + // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings. + return 2 /* Type */ | 1 /* Value */; + } else { return 1 /* Value */; } @@ -88878,7 +88894,6 @@ var ts; function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { switch (triggerCharacter) { case ".": - case "/": case "@": return true; case '"': @@ -88889,6 +88904,10 @@ var ts; case "<": // Opening JSX tag return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 199 /* BinaryExpression */; + case "/": + return ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); default: return ts.Debug.assertNever(triggerCharacter); } @@ -89543,13 +89562,7 @@ var ts; } break; case 178 /* ImportType */: - if (direct.qualifier) { - // `import("foo").x` named import - directImports.push(direct); - } - else { - // TODO: GH#23879 - } + directImports.push(direct); break; default: ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); @@ -89630,8 +89643,13 @@ var ts; return; } if (decl.kind === 178 /* ImportType */) { - if (decl.qualifier) { // TODO: GH#23879 - singleReferences.push(decl.qualifier.kind === 71 /* Identifier */ ? decl.qualifier : decl.qualifier.right); + if (decl.qualifier) { + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2 /* ExportEquals */) { + singleReferences.push(decl.argument.literal); } return; } @@ -90216,7 +90234,7 @@ var ts; if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles, sourceFilesSet); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -90231,34 +90249,36 @@ var ts; // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } - if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { - return getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet); + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export=" /* ExportEquals */); + // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + // Continue to get references to 'export ='. + symbol = ts.skipAlias(exportEquals, checker); + node = undefined; } - return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; - function isModuleReferenceLocation(node) { - if (!ts.isStringLiteralLike(node)) { - return false; - } - switch (node.parent.kind) { - case 238 /* ModuleDeclaration */: - case 253 /* ExternalModuleReference */: - case 243 /* ImportDeclaration */: - case 249 /* ExportDeclaration */: - return true; - case 177 /* LiteralType */: - return ts.isImportTypeNode(node.parent.parent); - case 186 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent); - default: - return false; - } + function isModuleSymbol(symbol) { + return symbol.flags & 1536 /* Module */ && ts.find(symbol.declarations, ts.isSourceFile); } - function getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet) { + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); - var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } + // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. return { type: "node", node: reference.literal }; } else { @@ -90281,10 +90301,11 @@ var ts; } break; default: + // This may be merged with something. ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; + return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -90312,17 +90333,17 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; - var state = new State(sourceFiles, sourceFilesSet, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); - if (node.kind === 79 /* DefaultKeyword */) { + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); + if (node && node.kind === 79 /* DefaultKeyword */) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -90441,7 +90462,7 @@ var ts; // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; /** @@ -90485,11 +90506,8 @@ var ts; var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; - // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. - if (hasMatchingMeaning(singleRef, state) && - !(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) { + if (shouldAddSingleReference(singleRef, state)) addRef(singleRef); - } } } // For each import, find all references to that import in its source file. @@ -90518,6 +90536,17 @@ var ts; } } } + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` + if (!ts.isIdentifier(singleRef)) + return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. + return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */); + } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -93227,7 +93256,9 @@ var ts; ? defaultImports[0] : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 - ? undefined + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); @@ -93274,7 +93305,7 @@ var ts; }; } function compareIdentifiers(s1, s2) { - return ts.compareStringsCaseSensitive(s1.text, s2.text); + return ts.compareStringsCaseInsensitive(s1.text, s2.text); } } OrganizeImports.coalesceImports = coalesceImports; @@ -93287,7 +93318,7 @@ var ts; var name2 = getExternalModuleName(m2); return ts.compareBooleans(name1 === undefined, name2 === undefined) || ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || - ts.compareStringsCaseSensitive(name1, name2); + ts.compareStringsCaseInsensitive(name1, name2); } OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); @@ -94387,6 +94418,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } + // Can't rename a module name. + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) + return undefined; var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -100200,7 +100234,7 @@ var ts; var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; } @@ -100317,12 +100351,6 @@ var ts; return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); } } - function usesJsExtensionOnImports(sourceFile) { - return ts.firstDefined(sourceFile.imports, function (_a) { - var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; - }) || false; - } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -100336,277 +100364,15 @@ var ts; ts.Debug.assertNever(kind); } } - function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) { - var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(sourceFile); + function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; - }); + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program, sourceFile, host, preferences); return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); }); // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - /** - * Looks for a existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(program, _a) { - var fileName = _a.fileName; - var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === fileName ? res.originalPath : undefined; - }); - }); - return symlinks.length === 0 ? [fileName] : symlinks; - } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } - function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { - for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); - return key.replace("*", matchedStar); - } - } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; - } - } - } - } - function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { - return undefined; - } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // 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 = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName)); - } - } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); - return isPathRelativeToParent(relativePath) ? undefined : relativePath; - }); - } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { - var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; - } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; - } - function isPathRelativeToParent(path) { - return ts.startsWith(path, ".."); - } function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) { var fromExistingImport = ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; @@ -100625,7 +100391,7 @@ var ts; var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences); + : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.host, ctx.preferences); for (var _i = 0, newImportInfos_1 = newImportInfos; _i < newImportInfos_1.length; _i++) { var info = newImportInfos_1[_i]; addNew.push(getCodeActionForNewImport(ctx, info)); @@ -101689,6 +101455,94 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + switch (container.kind) { + case 216 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements)); + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + break; + } + // falls through + case 218 /* WhileStatement */: + case 219 /* ForStatement */: + changes.deleteNode(sourceFile, container); + break; + default: + if (ts.isBlock(statement.parent)) { + split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); }); + } + else { + changes.deleteNode(sourceFile, statement); + } + } + } + function shouldRemove(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 235 /* InterfaceDeclaration */: + case 236 /* TypeAliasDeclaration */: + return true; + case 238 /* ModuleDeclaration */: + return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; + case 237 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + } + } + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + ts.Debug.assert(index !== -1); + return arr.slice(index); + } + // Calls 'cb' with the start and end of each range where 'pred' is true. + function split(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + var value = arr[i]; + if (pred(value)) { + start = start || value; + } + else { + if (start) { + cb(start, arr[i - 1]); + start = undefined; + } + } + } + if (start) + cb(start, arr[arr.length - 1]); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -102799,6 +102653,290 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +// Used by importFixes to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + // For each symlink/original for a module, returns a list of ways to import that file. + function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + var compilerOptions = program.getCompilerOptions(); + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var sourceDirectory = ts.getDirectoryPath(importingSourceFile.fileName); + return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + }) || false; + } + /** + * Looks for a existing imports that use symlinks to this module. + * Only if no symlink is available, the real path will be used. + */ + function getAllModulePaths(program, _a) { + var fileName = _a.fileName; + var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + }); + }); + return symlinks.length === 0 ? [fileName] : symlinks; + } + function getRelativePathNParents(relativePath) { + var components = ts.getPathComponents(relativePath); + if (components[0] || components.length === 1) + return 0; + for (var i = 1; i < components.length; i++) { + if (components[i] !== "..") + return i - 1; + } + return components.length - 1; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { + var roots = ts.getEffectiveTypeRoots(options, host); + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + // For a type definition, we can strip `/index` even with classic resolution. + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // 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 = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; + } + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName)); + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + var noExtension = ts.removeFileExtension(fileName); + return addJsExtension + ? noExtension + ".js" + : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { diff --git a/lib/typescript.js b/lib/typescript.js index 33caf6392fd..b920392a8d7 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -6735,6 +6735,8 @@ var ts; Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), }; })(ts || (ts = {})); var ts; @@ -10272,6 +10274,10 @@ var ts; } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { case 243 /* ImportDeclaration */: case 249 /* ExportDeclaration */: @@ -10281,12 +10287,13 @@ var ts; case 186 /* CallExpression */: return node.parent; case 177 /* LiteralType */: - return ts.cast(node.parent.parent, ts.isImportTypeNode); + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: - return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + return undefined; } } - ts.importFromModuleSpecifier = importFromModuleSpecifier; + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { case 243 /* ImportDeclaration */: @@ -27112,6 +27119,7 @@ var ts; function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864 /* JSContainer */) { + ts.Debug.assert(!!(target.flags & 33554432 /* Transient */)); // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { // reset flag when merging instantiated module into value module that has only const enums @@ -27139,6 +27147,10 @@ var ts; var sourceInitializer = ts.getJSInitializerSymbol(source); var targetInitializer = ts.getJSInitializerSymbol(target); if (sourceInitializer !== source || targetInitializer !== target) { + if (!(targetInitializer.flags & 33554432 /* Transient */)) { + var mergedInitializer = getMergedSymbol(targetInitializer); + targetInitializer = mergedInitializer === targetInitializer ? cloneSymbol(targetInitializer) : mergedInitializer; + } mergeSymbol(targetInitializer, sourceInitializer); } } @@ -44155,7 +44167,7 @@ var ts; checkGrammarForGenerator(node); } var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); if (isTypeAny(type)) { return type; } @@ -84265,6 +84277,10 @@ var ts; ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName return 2 /* Type */; } + else if (ts.isLiteralTypeNode(node.parent)) { + // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings. + return 2 /* Type */ | 1 /* Value */; + } else { return 1 /* Value */; } @@ -88878,7 +88894,6 @@ var ts; function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { switch (triggerCharacter) { case ".": - case "/": case "@": return true; case '"': @@ -88889,6 +88904,10 @@ var ts; case "<": // Opening JSX tag return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 199 /* BinaryExpression */; + case "/": + return ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); default: return ts.Debug.assertNever(triggerCharacter); } @@ -89543,13 +89562,7 @@ var ts; } break; case 178 /* ImportType */: - if (direct.qualifier) { - // `import("foo").x` named import - directImports.push(direct); - } - else { - // TODO: GH#23879 - } + directImports.push(direct); break; default: ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); @@ -89630,8 +89643,13 @@ var ts; return; } if (decl.kind === 178 /* ImportType */) { - if (decl.qualifier) { // TODO: GH#23879 - singleReferences.push(decl.qualifier.kind === 71 /* Identifier */ ? decl.qualifier : decl.qualifier.right); + if (decl.qualifier) { + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2 /* ExportEquals */) { + singleReferences.push(decl.argument.literal); } return; } @@ -90216,7 +90234,7 @@ var ts; if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles, sourceFilesSet); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -90231,34 +90249,36 @@ var ts; // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } - if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { - return getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet); + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export=" /* ExportEquals */); + // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + // Continue to get references to 'export ='. + symbol = ts.skipAlias(exportEquals, checker); + node = undefined; } - return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; - function isModuleReferenceLocation(node) { - if (!ts.isStringLiteralLike(node)) { - return false; - } - switch (node.parent.kind) { - case 238 /* ModuleDeclaration */: - case 253 /* ExternalModuleReference */: - case 243 /* ImportDeclaration */: - case 249 /* ExportDeclaration */: - return true; - case 177 /* LiteralType */: - return ts.isImportTypeNode(node.parent.parent); - case 186 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent); - default: - return false; - } + function isModuleSymbol(symbol) { + return symbol.flags & 1536 /* Module */ && ts.find(symbol.declarations, ts.isSourceFile); } - function getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet) { + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); - var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } + // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. return { type: "node", node: reference.literal }; } else { @@ -90281,10 +90301,11 @@ var ts; } break; default: + // This may be merged with something. ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; + return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -90312,17 +90333,17 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; - var state = new State(sourceFiles, sourceFilesSet, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); - if (node.kind === 79 /* DefaultKeyword */) { + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); + if (node && node.kind === 79 /* DefaultKeyword */) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -90441,7 +90462,7 @@ var ts; // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; /** @@ -90485,11 +90506,8 @@ var ts; var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; - // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. - if (hasMatchingMeaning(singleRef, state) && - !(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) { + if (shouldAddSingleReference(singleRef, state)) addRef(singleRef); - } } } // For each import, find all references to that import in its source file. @@ -90518,6 +90536,17 @@ var ts; } } } + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` + if (!ts.isIdentifier(singleRef)) + return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. + return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */); + } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -93227,7 +93256,9 @@ var ts; ? defaultImports[0] : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 - ? undefined + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); @@ -93274,7 +93305,7 @@ var ts; }; } function compareIdentifiers(s1, s2) { - return ts.compareStringsCaseSensitive(s1.text, s2.text); + return ts.compareStringsCaseInsensitive(s1.text, s2.text); } } OrganizeImports.coalesceImports = coalesceImports; @@ -93287,7 +93318,7 @@ var ts; var name2 = getExternalModuleName(m2); return ts.compareBooleans(name1 === undefined, name2 === undefined) || ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || - ts.compareStringsCaseSensitive(name1, name2); + ts.compareStringsCaseInsensitive(name1, name2); } OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); @@ -94387,6 +94418,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } + // Can't rename a module name. + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) + return undefined; var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -100200,7 +100234,7 @@ var ts; var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; } @@ -100317,12 +100351,6 @@ var ts; return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); } } - function usesJsExtensionOnImports(sourceFile) { - return ts.firstDefined(sourceFile.imports, function (_a) { - var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; - }) || false; - } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -100336,277 +100364,15 @@ var ts; ts.Debug.assertNever(kind); } } - function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) { - var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(sourceFile); + function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; - }); + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program, sourceFile, host, preferences); return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); }); // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - /** - * Looks for a existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(program, _a) { - var fileName = _a.fileName; - var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === fileName ? res.originalPath : undefined; - }); - }); - return symlinks.length === 0 ? [fileName] : symlinks; - } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } - function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { - for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); - return key.replace("*", matchedStar); - } - } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; - } - } - } - } - function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { - return undefined; - } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // 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 = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName)); - } - } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); - return isPathRelativeToParent(relativePath) ? undefined : relativePath; - }); - } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { - var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; - } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; - } - function isPathRelativeToParent(path) { - return ts.startsWith(path, ".."); - } function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) { var fromExistingImport = ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; @@ -100625,7 +100391,7 @@ var ts; var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences); + : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.host, ctx.preferences); for (var _i = 0, newImportInfos_1 = newImportInfos; _i < newImportInfos_1.length; _i++) { var info = newImportInfos_1[_i]; addNew.push(getCodeActionForNewImport(ctx, info)); @@ -101689,6 +101455,94 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + switch (container.kind) { + case 216 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements)); + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + break; + } + // falls through + case 218 /* WhileStatement */: + case 219 /* ForStatement */: + changes.deleteNode(sourceFile, container); + break; + default: + if (ts.isBlock(statement.parent)) { + split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); }); + } + else { + changes.deleteNode(sourceFile, statement); + } + } + } + function shouldRemove(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 235 /* InterfaceDeclaration */: + case 236 /* TypeAliasDeclaration */: + return true; + case 238 /* ModuleDeclaration */: + return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; + case 237 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + } + } + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + ts.Debug.assert(index !== -1); + return arr.slice(index); + } + // Calls 'cb' with the start and end of each range where 'pred' is true. + function split(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + var value = arr[i]; + if (pred(value)) { + start = start || value; + } + else { + if (start) { + cb(start, arr[i - 1]); + start = undefined; + } + } + } + if (start) + cb(start, arr[arr.length - 1]); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -102799,6 +102653,290 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +// Used by importFixes to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + // For each symlink/original for a module, returns a list of ways to import that file. + function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + var compilerOptions = program.getCompilerOptions(); + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var sourceDirectory = ts.getDirectoryPath(importingSourceFile.fileName); + return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + }) || false; + } + /** + * Looks for a existing imports that use symlinks to this module. + * Only if no symlink is available, the real path will be used. + */ + function getAllModulePaths(program, _a) { + var fileName = _a.fileName; + var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + }); + }); + return symlinks.length === 0 ? [fileName] : symlinks; + } + function getRelativePathNParents(relativePath) { + var components = ts.getPathComponents(relativePath); + if (components[0] || components.length === 1) + return 0; + for (var i = 1; i < components.length; i++) { + if (components[i] !== "..") + return i - 1; + } + return components.length - 1; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { + var roots = ts.getEffectiveTypeRoots(options, host); + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + // For a type definition, we can strip `/index` even with classic resolution. + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // 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 = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; + } + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName)); + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + var noExtension = ts.removeFileExtension(fileName); + return addJsExtension + ? noExtension + ".js" + : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 33caf6392fd..b920392a8d7 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -6735,6 +6735,8 @@ var ts; Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), }; })(ts || (ts = {})); var ts; @@ -10272,6 +10274,10 @@ var ts; } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { case 243 /* ImportDeclaration */: case 249 /* ExportDeclaration */: @@ -10281,12 +10287,13 @@ var ts; case 186 /* CallExpression */: return node.parent; case 177 /* LiteralType */: - return ts.cast(node.parent.parent, ts.isImportTypeNode); + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: - return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + return undefined; } } - ts.importFromModuleSpecifier = importFromModuleSpecifier; + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { case 243 /* ImportDeclaration */: @@ -27112,6 +27119,7 @@ var ts; function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864 /* JSContainer */) { + ts.Debug.assert(!!(target.flags & 33554432 /* Transient */)); // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { // reset flag when merging instantiated module into value module that has only const enums @@ -27139,6 +27147,10 @@ var ts; var sourceInitializer = ts.getJSInitializerSymbol(source); var targetInitializer = ts.getJSInitializerSymbol(target); if (sourceInitializer !== source || targetInitializer !== target) { + if (!(targetInitializer.flags & 33554432 /* Transient */)) { + var mergedInitializer = getMergedSymbol(targetInitializer); + targetInitializer = mergedInitializer === targetInitializer ? cloneSymbol(targetInitializer) : mergedInitializer; + } mergeSymbol(targetInitializer, sourceInitializer); } } @@ -44155,7 +44167,7 @@ var ts; checkGrammarForGenerator(node); } var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); if (isTypeAny(type)) { return type; } @@ -84265,6 +84277,10 @@ var ts; ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName return 2 /* Type */; } + else if (ts.isLiteralTypeNode(node.parent)) { + // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings. + return 2 /* Type */ | 1 /* Value */; + } else { return 1 /* Value */; } @@ -88878,7 +88894,6 @@ var ts; function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { switch (triggerCharacter) { case ".": - case "/": case "@": return true; case '"': @@ -88889,6 +88904,10 @@ var ts; case "<": // Opening JSX tag return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 199 /* BinaryExpression */; + case "/": + return ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); default: return ts.Debug.assertNever(triggerCharacter); } @@ -89543,13 +89562,7 @@ var ts; } break; case 178 /* ImportType */: - if (direct.qualifier) { - // `import("foo").x` named import - directImports.push(direct); - } - else { - // TODO: GH#23879 - } + directImports.push(direct); break; default: ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); @@ -89630,8 +89643,13 @@ var ts; return; } if (decl.kind === 178 /* ImportType */) { - if (decl.qualifier) { // TODO: GH#23879 - singleReferences.push(decl.qualifier.kind === 71 /* Identifier */ ? decl.qualifier : decl.qualifier.right); + if (decl.qualifier) { + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2 /* ExportEquals */) { + singleReferences.push(decl.argument.literal); } return; } @@ -90216,7 +90234,7 @@ var ts; if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles, sourceFilesSet); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -90231,34 +90249,36 @@ var ts; // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } - if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { - return getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet); + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export=" /* ExportEquals */); + // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + // Continue to get references to 'export ='. + symbol = ts.skipAlias(exportEquals, checker); + node = undefined; } - return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; - function isModuleReferenceLocation(node) { - if (!ts.isStringLiteralLike(node)) { - return false; - } - switch (node.parent.kind) { - case 238 /* ModuleDeclaration */: - case 253 /* ExternalModuleReference */: - case 243 /* ImportDeclaration */: - case 249 /* ExportDeclaration */: - return true; - case 177 /* LiteralType */: - return ts.isImportTypeNode(node.parent.parent); - case 186 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent); - default: - return false; - } + function isModuleSymbol(symbol) { + return symbol.flags & 1536 /* Module */ && ts.find(symbol.declarations, ts.isSourceFile); } - function getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet) { + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); - var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } + // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. return { type: "node", node: reference.literal }; } else { @@ -90281,10 +90301,11 @@ var ts; } break; default: + // This may be merged with something. ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; + return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -90312,17 +90333,17 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; - var state = new State(sourceFiles, sourceFilesSet, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); - if (node.kind === 79 /* DefaultKeyword */) { + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); + if (node && node.kind === 79 /* DefaultKeyword */) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -90441,7 +90462,7 @@ var ts; // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; /** @@ -90485,11 +90506,8 @@ var ts; var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; - // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. - if (hasMatchingMeaning(singleRef, state) && - !(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) { + if (shouldAddSingleReference(singleRef, state)) addRef(singleRef); - } } } // For each import, find all references to that import in its source file. @@ -90518,6 +90536,17 @@ var ts; } } } + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` + if (!ts.isIdentifier(singleRef)) + return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. + return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */); + } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -93227,7 +93256,9 @@ var ts; ? defaultImports[0] : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 - ? undefined + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); @@ -93274,7 +93305,7 @@ var ts; }; } function compareIdentifiers(s1, s2) { - return ts.compareStringsCaseSensitive(s1.text, s2.text); + return ts.compareStringsCaseInsensitive(s1.text, s2.text); } } OrganizeImports.coalesceImports = coalesceImports; @@ -93287,7 +93318,7 @@ var ts; var name2 = getExternalModuleName(m2); return ts.compareBooleans(name1 === undefined, name2 === undefined) || ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || - ts.compareStringsCaseSensitive(name1, name2); + ts.compareStringsCaseInsensitive(name1, name2); } OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); @@ -94387,6 +94418,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } + // Can't rename a module name. + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) + return undefined; var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -100200,7 +100234,7 @@ var ts; var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; } @@ -100317,12 +100351,6 @@ var ts; return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); } } - function usesJsExtensionOnImports(sourceFile) { - return ts.firstDefined(sourceFile.imports, function (_a) { - var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; - }) || false; - } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -100336,277 +100364,15 @@ var ts; ts.Debug.assertNever(kind); } } - function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) { - var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(sourceFile); + function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; - }); + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program, sourceFile, host, preferences); return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); }); // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - /** - * Looks for a existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(program, _a) { - var fileName = _a.fileName; - var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === fileName ? res.originalPath : undefined; - }); - }); - return symlinks.length === 0 ? [fileName] : symlinks; - } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } - function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { - for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); - return key.replace("*", matchedStar); - } - } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; - } - } - } - } - function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { - return undefined; - } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // 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 = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName)); - } - } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); - return isPathRelativeToParent(relativePath) ? undefined : relativePath; - }); - } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { - var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; - } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; - } - function isPathRelativeToParent(path) { - return ts.startsWith(path, ".."); - } function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) { var fromExistingImport = ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; @@ -100625,7 +100391,7 @@ var ts; var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences); + : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.host, ctx.preferences); for (var _i = 0, newImportInfos_1 = newImportInfos; _i < newImportInfos_1.length; _i++) { var info = newImportInfos_1[_i]; addNew.push(getCodeActionForNewImport(ctx, info)); @@ -101689,6 +101455,94 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + switch (container.kind) { + case 216 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements)); + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + break; + } + // falls through + case 218 /* WhileStatement */: + case 219 /* ForStatement */: + changes.deleteNode(sourceFile, container); + break; + default: + if (ts.isBlock(statement.parent)) { + split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); }); + } + else { + changes.deleteNode(sourceFile, statement); + } + } + } + function shouldRemove(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 235 /* InterfaceDeclaration */: + case 236 /* TypeAliasDeclaration */: + return true; + case 238 /* ModuleDeclaration */: + return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; + case 237 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + } + } + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + ts.Debug.assert(index !== -1); + return arr.slice(index); + } + // Calls 'cb' with the start and end of each range where 'pred' is true. + function split(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + var value = arr[i]; + if (pred(value)) { + start = start || value; + } + else { + if (start) { + cb(start, arr[i - 1]); + start = undefined; + } + } + } + if (start) + cb(start, arr[arr.length - 1]); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -102799,6 +102653,290 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +// Used by importFixes to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + // For each symlink/original for a module, returns a list of ways to import that file. + function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + var compilerOptions = program.getCompilerOptions(); + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var sourceDirectory = ts.getDirectoryPath(importingSourceFile.fileName); + return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + }) || false; + } + /** + * Looks for a existing imports that use symlinks to this module. + * Only if no symlink is available, the real path will be used. + */ + function getAllModulePaths(program, _a) { + var fileName = _a.fileName; + var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + }); + }); + return symlinks.length === 0 ? [fileName] : symlinks; + } + function getRelativePathNParents(relativePath) { + var components = ts.getPathComponents(relativePath); + if (components[0] || components.length === 1) + return 0; + for (var i = 1; i < components.length; i++) { + if (components[i] !== "..") + return i - 1; + } + return components.length - 1; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { + var roots = ts.getEffectiveTypeRoots(options, host); + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + // For a type definition, we can strip `/index` even with classic resolution. + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // 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 = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; + } + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName)); + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + var noExtension = ts.removeFileExtension(fileName); + return addJsExtension + ? noExtension + ".js" + : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index b0edb96170f..b853404b9a4 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -4672,6 +4672,8 @@ var ts; Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), }; })(ts || (ts = {})); var ts; @@ -6127,6 +6129,10 @@ var ts; } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { case 243: case 249: @@ -6136,12 +6142,13 @@ var ts; case 186: return node.parent; case 177: - return ts.cast(node.parent.parent, ts.isImportTypeNode); + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: - return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + return undefined; } } - ts.importFromModuleSpecifier = importFromModuleSpecifier; + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { case 243: